Does jQuery's parseHTML() mean that I can take any string of HTML code and treat it as if were in the DOM? Can I manipulate the string of HTML by finding elements using selectors, replacing elements, calling ("destroy") on plugins, getting element index and all that other stuff that can be done with elements in the DOM, but with the changes applying to the string of HTML held by a variable?
1 Answer
parseHTML() will return the top level node as a DOM element, which you then can manipulate as a DOM element. If you pass a string to parseHTML() that is not encapsulated by one tag, it will split up the string into separate DOM elements.
Sample 1:
var html = $.parseHTML("<div id='#first'><div id='#second'><span>testing</span></div></div>");
$.each( html, function( i, el ) {
console.log(el.nodeName ? "true" : "false");
});
/* Outputs:
true
*/
Sample 2:
var html2 = $.parseHTML("Sample string with <strong>bold</strong> and a <div>div</div>.");
$.each( html2, function( i, el ) {
console.log(el.nodeName ? "true" : "false");
});
/* Outputs:
true
true
true
true
true
*/
In the first sample, one DOM element is created containing nested set of elements. In the second, the string is split into five separate DOM elements: three text elements, one <strong></strong>, and one <div></div>.
NOTE: (el.nodeName ? "true" : "false") will return true if the element is a DOM element.
Also, to answer your last question, changes applied to these resulting DOM elements will not be reflected in the variable holding your original element (in this case, var html or var html2)