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.
- 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
4 Answers
Reset to default 20Take 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
版权声明:本文标题:javascript - Convert a string of HTML into DOM objects with jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738042915a2054103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论