admin管理员组

文章数量:1178593

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.

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.

Share Improve this question edited Dec 29, 2011 at 17:00 David Rivers 2,9451 gold badge32 silver badges40 bronze badges asked Dec 25, 2011 at 19:46 Vineel Kumar ReddyVineel Kumar Reddy 4,7169 gold badges34 silver badges38 bronze badges 8
  • HTML should never be in a string in JavaScript. – Raynos Commented Dec 25, 2011 at 20:06
  • 3 @Raynos: That's not very true. What if you get some pre-rendered HTML from the server? – SLaks Commented Dec 25, 2011 at 20:34
  • 1 Please edit your question to acknowledge that you are using a convenience library like jQuery. I spent unnecessary time writing native JavaScript code. – David Rivers Commented Dec 25, 2011 at 20:41
  • @SLaks I agree it's not completely true. What is true however, is HTML should never be in a string in JavaScript application code. It's acceptable as a hidden layer in a library. – Raynos Commented Dec 25, 2011 at 21:14
  • @Raynos: You mean that HTML strings should never explicitly appear in Javascript source code. Yes. – SLaks Commented Dec 25, 2011 at 21:25
 |  Show 3 more comments

4 Answers 4

Reset to default 20

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;

Create a dummy element and set its innerHTML to your HTML string.

// Construct a container as a placeholder for your content

var container = document.createElement('div');
container.id = 'container';

// Inject the container into the DOM

document.body.appendChild(container);

// Populate the injected container with your content

container.innerHtml = '<p id="pTag">I am a <em>P</em> tag with some <strong>nested markup</strong>.</p>';

To convert Html text into a Jquery-Object use the $() function:

div = '<div>hello world</div>';
$div = $(div);

But as others have noted in most cases you don't need that because DOM manipulation functions like append() and prepend() will accept plain text, so

$('body').append('<div>hello world</div>');

is absolutely fine.

本文标签: javascriptConvert a string of HTML into DOM objects with jQueryStack Overflow