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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3103962/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:16:57  来源:igfitidea点击:

Converting HTML string into DOM elements?

javascripthtmldom

提问by Tower

Is there a way to convert HTML like:

有没有办法转换HTML,如:

<div>
<a href="#"></a>
<span></span>
</div>

or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().

或任何其他 HTML 字符串到 DOM 元素?(这样我就可以使用 appendChild())。我知道我可以做 .innerHTML 和 .innerText,但这不是我想要的——我真的希望能够将动态 HTML 字符串转换为 DOM 元素,以便我可以在 .appendChild() 中传递它。

Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.

更新:似乎有混淆。我有一个字符串中的 HTML 内容,作为 JavaScript 中变量的值。文档中没有 HTML 内容。

回答by maerics

You can use a DOMParser, like so:

您可以使用 a DOMParser,如下所示:

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link

回答by bobince

You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:

您通常会创建一个临时父元素,您可以在其中写入innerHTML,然后提取内容:

var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><a href="#"></a><span></span></div>';
var div= wrapper.firstChild;

If the element whose outer-HTML you've got is a simple <div>as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.

如果您获得的外部 HTML 元素<div>像这里一样简单,那么这很容易。如果它可能是其他任何地方都不能去的东西,那么您可能会遇到更多问题。例如,如果它是 a <li>,则您必须将父包装器设为 a <ul>

But IE can't write innerHTMLon elements like <tr>so if you had a <td>you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write thatto innerHTMLand extricate the actual <td>you wanted from a couple of levels down.

但IE不能写innerHTML上相似的元素<tr>,如果你有一个这样<td>你必须包装在整个HTML串<table><tbody><tr>...... </tr></tbody></table>,写的是innerHTML和解脱实际<td>你从几个级别的下降通缉。

回答by Ram

Why not use insertAdjacentHTML

为什么不使用insertAdjacentHTML

for example:

例如:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

回答by orip

Check out John Resig's pure JavaScript HTML parser.

查看 John Resig 的纯 JavaScript HTML 解析器

EDIT: if you want the browser to parse the HTML for you, innerHTMLis exactly what you want. From this SO question:

编辑:如果您希望浏览器为您解析 HTML,innerHTML这正是您想要的。从这个问题

var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;

回答by Tower

Okay, I realized the answer myself, after I had to think about other people's answers. :P

好吧,在我不得不考虑其他人的答案之后,我自己意识到了答案。:P

var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);

回答by Filling The Stack is What I DO

Here is a little code that is useful.

这是一个有用的小代码。

var uiHelper = function () {

var htmls = {};

var getHTML = function (url) {
                /// <summary>Returns HTML in a string format</summary>
                /// <param name="url" type="string">The url to the file with the HTML</param>

    if (!htmls[url])
    {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    htmls[url] = xmlhttp.responseText;
     };
     return htmls[url];
    };

        return {
            getHTML: getHTML
        };
}();

--Convert the HTML string into a DOM Element

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

String.prototype.toDomElement = function () {

        var wrapper = document.createElement('div');
        wrapper.innerHTML = this;
        var df= document.createDocumentFragment();
        return df.addChilds(wrapper.children);
};

--prototype helper

--原型助手

HTMLElement.prototype.addChilds = function (newChilds) {
        /// <summary>Add an array of child elements</summary>
        /// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
        /// <returns type="this" />
        for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
        return this;
};

--Usage

- 用法

 thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();

回答by Sarfraz

Just give an idto the element and process it normally eg:

只需给id元素一个并正常处理它,例如:

<div id="dv">
<a href="#"></a>
<span></span>
</div>

Now you can do like:

现在你可以这样做:

var div = document.getElementById('dv');
div.appendChild(......);

Or with jQuery:

或者使用 jQuery:

$('#dv').get(0).appendChild(........);

回答by william malo

You can do it like this:

你可以这样做:

String.prototype.toDOM=function(){
  var d=document
     ,i
     ,a=d.createElement("div")
     ,b=d.createDocumentFragment();
  a.innerHTML=this;
  while(i=a.firstChild)b.appendChild(i);
  return b;
};

var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);