将 HTML 字符串转换为 DOM 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16816726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting an HTML string to a DOM element?
提问by Niet the Dark Absol
Say one has,
说有,
var some_html = '<div class = "am_hold">' +
'<img name="bo_im" id="' + val.id + '" class="bookmark_image" src="' + val.favicon + '">' +
'<a target="_blank" name="bookmark_link" class="bookmark_link" href = "' +
val.url + '" id="' + val.id + '">' + val.title + '</a>' +
'<div><div class = "bookmark_menu"></div></div>' +
'</div>';
is it possible to do
有没有可能做
var some_element = `some_function`(some_html);
Is there an implementation for some_function (1) with out using a library and (2) with using a library.
是否有 some_function (1) 不使用库和 (2) 使用库的实现。
回答by Niet the Dark Absol
Create a temporary container for your HTML, then gets its content. Something like:
为您的 HTML 创建一个临时容器,然后获取其内容。就像是:
var d = document.createElement('div');
d.innerHTML = some_html;
return d.firstChild;
回答by Nirus
Try the below code
试试下面的代码
var myname = 'John Doe';
//This is using Jquery
var htmltext = '<p style="color:red">'+myname+'This is a test</p>'
$('#one').html(htmltext);
//This is pure javascript
document.getElementById('two').innerHTML='<p style="color:red">'+myname+'This is a test</p>';
I am building a string and appending it to an html element using html() rather than text() function . This will be treated as a HTML tag by browser and diplay the changes in the UI as seen in the fiddle.
我正在构建一个字符串并使用 html() 而不是 text() 函数将其附加到一个 html 元素。这将被浏览器视为 HTML 标记,并在 UI 中显示更改,如小提琴所示。
回答by DonnyDee
jQuery.parseHTML()-function might help you.
jQuery.parseHTML()-function 可能会帮助你。