I have HTML in a JavaScript string (containing usual, nested HTML). Using jQuery, can I convert that into a valid HTML element in a single stroke using any of the document.create
* functions? My requirement is to use document.getElementById
on the created DOM object.
Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.
The simplest way to do this is to create an element, insert the string into with innerHTML , then return the element. /** * Convert a template string into HTML DOM nodes * @param {String} str The template string * @return {Node} The template HTML */ var stringToHTML = function (str) { var dom = document.
Take simple nested example.
var dom_string = '<div>xxx<div>yyy</div></div>';
create HTML DOM elements using $() function of jquery and append wherever you want. i have taken 'body' but you can append anywhere.
$(dom_string).appendTo('body');
Alternatively you can implement this with pure javascript:
var dom_target = document.getElementById("target");
dom_target.innerHTML = dom_string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With