Javascript 如何正确使用 innerHTML 从 html 字符串创建元素(带有可能的子元素)?

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

How to correctly use innerHTML to create an element (with possible children) from a html string?

javascriptstringdominnerhtml

提问by Sanchit

Note: I do NOTwant to use any framework.

注:我希望使用任何框架。



The goal is just to create a function that will return an element based on an HTML string.

目标只是创建一个函数,该函数将基于 HTML 字符串返回一个元素。


Assume a simple HTML Document like such:


假设一个简单的 HTML 文档像这样:

<html>
<head></head>
<body>
</body>
</html>

All functions mentioned are in included the head section and all DOM creation/manipulation is done at the end of the body in a script tag.

提到的所有函数都包含在 head 部分中,所有 DOM 创建/操作都在脚本标记的正文末尾完成。



I have a function createElement that takes a well formed HTML String as an argument. It goes like this:

我有一个函数 createElement ,它采用格式良好的 HTML 字符串作为参数。它是这样的:

function createElement(str)
{
  var div = document.createElement('div');
  div.innerHTML = str;
  return div.childNodes;
}

Now this functions works great when you call it like such:

现在,当您像这样调用它时,此函数效果很好:

var e = createElement('<p id="myId" class="myClass">myInnerHTML</p>');

With the minor (possibly HUGE) problem that the element created isn't a 'true' element, it still has a parentNode of 'div'. If anyone knows how to fix that, then that would be awesome.

由于创建的元素不是“真实”元素的次要(可能是巨大的)问题,它仍然具有“div”的 parentNode。如果有人知道如何解决这个问题,那就太棒了。



Now if I call the same function with a more complex string:

现在,如果我使用更复杂的字符串调用相同的函数:

var e = createElement('<p id="myId" class="myClass">innerHTML<h2 id="h2ID" class="h2CLASS">Heading2</h2></p>');

It creates TWO children instead of ONE child with another child having another child.

Once you do div.innerHTML = str. The innerHTML instead of

它创建了两个孩子,而不是一个孩子,另一个孩子有另一个孩子。

一旦你做 div.innerHTML = str. innerHTML 而不是

`<p id="myId" class="myClass">innerHTML    <h2 id="h2ID" class="h2CLASS">Heading2</h2>    </p>`

turns to

转向

`<p id="myId" class="myClass">innerHTML</p>        <h2 id="h2ID" class="h2CLASS">Heading2</h2>`



Questions:问题:

  1. Can I somehow get an element without a parent node after using .innerHTML?
  2. Can I (in the case of the slightly complex string) get my function to return ONE element with the appropriate child instead of two elements. [It actually returns three, <p.myClass#myId>,<h2.h2CLASS#h2ID>, and another <p>]
  1. 使用 .innerHTML 后,我可以以某种方式获得没有父节点的元素吗?
  2. 我可以(在稍微复杂的字符串的情况下)让我的函数返回一个带有适当子元素的元素而不是两个元素。[它实际上返回三个, <p.myClass#myId>, <h2.h2CLASS#h2ID>, 和另一个<p>]

采纳答案by user113716

This is similar to the answer from palswim, except that it doesn't bother with creating a clone, and uses a while()loop instead, always appending the node at [0].

这类似于来自 的答案palswim,不同之处在于它不打扰创建克隆,while()而是使用循环,始终将节点附加到[0]

function createElement( str ) {
    var frag = document.createDocumentFragment();

    var elem = document.createElement('div');
    elem.innerHTML = str;

    while (elem.childNodes[0]) {
        frag.appendChild(elem.childNodes[0]);
    }
    return frag;
}

回答by palswim

You'd have to attach the new element somewhere. Try using a DocumentFragmentobject in conjunction with the divyou created:

您必须将新元素附加到某处。尝试将DocumentFragment对象与div您创建的对象结合使用:

function createElement(str) {
    var div = document.createElement('div');
    div.innerHTML = str;
    var container = document.createDocumentFragment();
    for (var i=0; i < div.childNodes.length; i++) {
        var node = div.childNodes[i].cloneNode(true);
        container.appendChild(node);
    }
    return container.childNodes;
}

It's more overhead, but it does what you want. Note that DOM elements' .insertAdjacentHTMLmember function is coming in HTML5.

它的开销更大,但它可以满足您的需求。请注意,DOM 元素的.insertAdjacentHTML成员函数来自 HTML5。

For that complex string you passed, it isn't valid XHTML syntax - you can't have a block element as a child of <p>(<h2>is a block level element).

对于您传递的那个复杂字符串,它不是有效的 XHTML 语法 - 您不能将块元素作为<p>(<h2>是块级元素)的子元素。