Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string of HTML into DOM objects with jQuery

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.

like image 468
Vineel Kumar Reddy Avatar asked Dec 25 '11 19:12

Vineel Kumar Reddy


People also ask

How can create DOM element in jQuery?

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.

How do I turn a String into an HTML element?

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.


1 Answers

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;
like image 132
P K Avatar answered Sep 20 '22 13:09

P K