I would like to create a DOM node, set the 'id' attribute and then append it to 'body'. The following seems not to work because jQuery doesn't see my template as an object:
var template = "<li><div class='bar'>bla</div></li>"; template.find('li').attr('id','1234'); $(body).append(template);
How can I tell jQuery to treat this as an object so find() works on it?
The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node object.
Inserting Nodes into the DOM The methods appendChild() and insertBefore() are used to add items to the beginning, middle, or end of a parent element, and replaceChild() is used to replace an old node with a new node.
The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
I'd put it in the DOM first. I'm not sure why my first example failed. That's really weird.
var e = $("<ul><li><div class='bar'>bla</div></li></ul>"); $('li', e).attr('id','a1234'); // set the attribute $('body').append(e); // put it into the DOM
Putting e (the returns elements) gives jQuery context under which to apply the CSS selector. This keeps it from applying the ID to other elements in the DOM tree.
The issue appears to be that you aren't using the UL. If you put a naked li in the DOM tree, you're going to have issues. I thought it could handle/workaround this, but it can't.
You may not be putting naked LI's in your DOM tree for your "real" implementation, but the UL's are necessary for this to work. Sigh.
Example: http://jsbin.com/iceqo
By the way, you may also be interested in microtemplating.
Try this:
var div = $('<div></div>').addClass('bar').text('bla'); var li = $('<li></li>').attr('id', '1234'); li.append(div); $('body').append(li);
Obviously, it doesn't make sense to append a li to the body directly. Basically, the trick is to construct the DOM elementr tree with $('your html here'). I suggest to use CSS modifiers (.text(), .addClass() etc) as opposed to making jquery parse raw HTML, it will make it much easier to change things later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With