Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use jQuery selectors on an HTML string that is not attached to the DOM?

Tags:

jquery

So if I have a variable like

var ht = "<body><p>Paragraph Here</p></body>" 

If it was attached to the DOM I could just do this to get the text

$('p').text();  

But can I do the same kind of selection just on a variable that has not yet been attached to the dom?

like image 301
etoisarobot Avatar asked Dec 02 '10 15:12

etoisarobot


People also ask

Does jQuery use dom?

JavaScript / jQuery HTML DOM jQuery was created in 2006 by John Resig. It was designed to handle Browser Incompatibilities and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax. For more than 10 years, jQuery has been the most popular JavaScript library in the world.

How do jQuery selectors work?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

What jQuery function is used to insert markup into the DOM?

append( function ) A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at the end of each element in the set of matched elements.


2 Answers

The jQuery object will take HTML and make it in to a DOM structure for further query, you can pass it in directly to create the object, or use it as a context if you just wish to query it.

Edit: For some reason it seems necessary to wrap it in a DIV, if not already within one in this example. See the jQuery object documentation on this method for further information.

See test framework for system at: http://jsfiddle.net/hUMqU/

var ht = "<body><p>Paragraph Here</p></body>"; $('<div>' + ht + '</div>').find('p').text(); 

or as context:

var ht = "<body><p>Paragraph Here</p></body>"; $('p', '<div>' + ht + '</div>').text(); 
like image 70
Orbling Avatar answered Sep 30 '22 03:09

Orbling


There is no mystery. Selecting

$('p')   

selects p elements of the document, the implied context.

But the p elements in:

var ht = "<body><p>Paragraph Here</p></body>";   

are not attached to the document (DOM) so it's OK if they are not selected.

Fortunately the $() function has a second argument, the context, that has to be used here, like:

$('p', $(ht).context)  
like image 39
Juan Lanus Avatar answered Sep 30 '22 04:09

Juan Lanus