使用内置的DOM方法或Prototype从HTML字符串创建新的DOM元素

923
我有一个表示元素的HTML字符串:'<li>text</li>',我想将其附加到DOM中的一个元素(在我的情况下是一个ul)。我该如何使用Prototype或DOM方法来实现这一点?(我知道在jQuery中很容易做到这一点,但不幸的是我们没有使用jQuery。)

2
抱歉,您究竟想要实现什么目标?将HTML字符串转换为DOM元素? - Crescent Fresh
86
这些解决方案过于间接,这让人感到不幸。我希望标准委员会能够指定类似的规范,例如:“var nodes = document.fromString('<b>Hello</b> <br>');” - Sridhar Sarnobat
1
我遇到了一个问题,因为我有一些需要传递的属性,而我不想解析它们:"<table id='5ccf9305-4b10-aec6-3c55-a6d218bfb107' class='data-table row-border display' cellspacing='0' width='100%'></table>"所以,我只是使用了:$("<table id='5ccf9305-4b10-aec6-3c55-a6d218bfb107' class='data-table row-border display' cellspacing='0' width='100%'></table>") - stevenlacerda
30个回答

1

我想分享一种过于复杂但又简单的方法,也许有人会发现其中的用处。

/*Creates a new element - By Jamin Szczesny*/
function _new(args){
    ele = document.createElement(args.node);
    delete args.node;
    for(x in args){ 
        if(typeof ele[x]==='string'){
            ele[x] = args[x];
        }else{
            ele.setAttribute(x, args[x]);
        }
    }
    return ele;
}

/*You would 'simply' use it like this*/

$('body')[0].appendChild(_new({
    node:'div',
    id:'my-div',
    style:'position:absolute; left:100px; top:100px;'+
          'width:100px; height:100px; border:2px solid red;'+
          'cursor:pointer; background-color:HoneyDew',
    innerHTML:'My newly created div element!',
    value:'for example only',
    onclick:"alert('yay')"
}));

记录一下,我试了一下这段代码 - 真是太棒了。我认为它将成为我从JSON动态创建HTML的首选方式 - 感谢你啊伙计!! - walbury

0
使用outerHTML怎么样?
*element*.appendChild( document.createElement('li')).outerHTML= '<li>text</li>' ;

createElement的参数不需要与字符串中指定的元素类型匹配,但它必须是element的合法子元素。

*element*.appendChild( document.createElement('a')).outerHTML= '<li>text</li>' ;

同样有效


-1
function domify (str) {
  var el = document.createElement('div');
  el.innerHTML = str;

  var frag = document.createDocumentFragment();
  return frag.appendChild(el.removeChild(el.firstChild));
}

var str = "<div class='foo'>foo</div>";
domify(str);

-1

使用最新的JS示例:

<template id="woof-sd-feature-box">
<div class="woof-sd-feature-box" data-key="__KEY__" data-title="__TITLE__" data-data="__OPTIONS__">
    <h4>__TITLE__</h4>
    <div class="woof-sd-form-item-anchor">
        <img src="img/move.png" alt="">
    </div>
</div>

</template>

<script>
create(example_object) {
        let html = document.getElementById('woof-sd-feature-box').innerHTML;
        html = html.replaceAll('__KEY__', example_object.dataset.key);
        html = html.replaceAll('__TITLE__', example_object.dataset.title);
        html = html.replaceAll('__OPTIONS__', example_object.dataset.data);
        //convertion HTML to DOM element and prepending it into another element
        const dom = (new DOMParser()).parseFromString(html, "text/html");
        this.container.prepend(dom.querySelector('.woof-sd-feature-box'));
    }
</script>

-1

我在这篇文章中添加了链接。( 将HTML字符串转换为DOM元素? )

对于我来说,我想找到一种将字符串转换为HTML元素的方法。如果你也有这个需求,可以尝试以下方法:

const frag = document.createRange().createContextualFragment(
`<a href="/link.js">js</a> 
 <a>go</a>
`
) 
const aCollection = frag.querySelectorAll("a")
for (let [key, a] of Object.entries(aCollection)) {
  console.log(a.getAttribute("href"), a.textContent)
}


-2
你可以使用下列函数将文本“HTML”转换为元素。

function htmlToElement(html)
{
  var element = document.createElement('div');
  element.innerHTML = html;
  return(element);
}
var html="<li>text and html</li>";
var e=htmlToElement(html);


-1;这是与被接受的答案中提出的技术相同的技术,具有相同的缺点 - 特别是不能用于“td”。 - Mark Amery

-3

这是对我有效的工作代码

我想将 'Text' 字符串转换为 HTML 元素

var diva = UWA.createElement('div');
diva.innerHTML = '<a href="http://wwww.example.com">Text</a>';
var aelement = diva.firstChild;

什么是 wwww - Tintin81

-3

var msg = "测试" jQuery.parseHTML(msg)


感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。一个适当的解释将极大地提高其长期价值,因为它可以展示为什么这是一个好的问题解决方案,并使其对未来读者在其他类似问题上更有用。请[编辑]您的答案以添加一些解释,包括您所做的假设。 - Dwhitz

-4
var jtag = $j.li({ child:'text' }); // Represents: <li>text</li>
var htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());

使用jnerator


-9

这也可以工作:

$('<li>').text('hello').appendTo('#mylist');

这更像是一种使用链接函数调用的jQuery方式。


33
感觉像 jQuery 是因为它确实是 jQuery 吗? - Tim Ferrell
6
那最后一句话真的太有趣了! - kumarharsh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接