且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将HTML字符串转换为DOM元素?

更新时间:2022-10-22 08:26:43

为您的HTML创建临时容器,然后获取其内容。例如:

  var d = document.createElement('div'); 
d.innerHTML = some_html;
返回d.firstChild;


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.

Create a temporary container for your HTML, then gets its content. Something like:

var d = document.createElement('div');
d.innerHTML = some_html;
return d.firstChild;