1

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 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure if I explained my question well enough. I want to manipulate a string of HTML and do other things with it, like append the string of changed HTML or download it in an HTML file with JavaScript. My question is if I can treat that HTML string as if it were in the DOM by being able to remove, append, find(etc) elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.