jquery selection of non-existing elements
in jquery when I use element that doesn't exist what happens? Consider:
$('<tmp/>').html(some_ht开发者_开发问答ml_string).text()
where I use nonexistent element <tmp/>
just to use functionality of html()
and text()
(to do some stuff).
and is this right approach or not?
Expanding upon the already existing answer, it just creates an HTML element that is not attached to anything. You'd have to insert it into the DOM before it could be used. This is fine for what you are wanting to do - have a dummy element so you can easily use .html()
and .text()
.
What you're doing here is calling the second jQuery method. To quote from the jQuery docs:
jQuery( html )
creates DOM elements on the fly from the provided string of raw HTML.If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML ... if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object.
In practice, this means that you will end up with a fully functional jQuery object - you can use this object to manipulate the HTML snippet you started with. This is pretty handy, and a perfectly valid approach.
The only other thing to keep in mind is that the snippet won't appear in the browser anywhere, unless you actually append it to the DOM.
Try it yourself: http://jsfiddle.net/
Basically it creates a node not attached to anything...
精彩评论