Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  159] [ 7]  / answers: 1 / hits: 171639  / 12 Years ago, fri, june 15, 2012, 12:00:00

I have a big HTML-string containing multiple child-nodes.



Is it possible to construct a jQuery DOM object using this string?



I've tried $(string) but it only returns an array containing all the individual nodes.



Imtrying to get an element which i can use the .find() function on.


More From » jquery

 Answers
7

Update:


From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:


var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO




var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO


What's happening in this code:



  • $('<div/>') is a fake <div> that does not exist in the DOM

  • $('<div/>').html(string) appends string within that fake <div> as children

  • .contents() retrieves the children of that fake <div> as a jQuery object


If you want to make .find() work then try this:


var string = '<div><input type="text" value="val" /></div>',
object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO


[#84878] Thursday, June 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katia

Total Points: 570
Total Questions: 101
Total Answers: 85

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;