javascript 不使用 jQuery 添加到 DOM

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

Add to DOM without jQuery

javascript

提问by user2143356

This should be simple, but it's not.

这应该很简单,但事实并非如此。

document.getElementsByTagName('body')[0].document.createTextNode( document.createElement('<div>some HTML</div>') );

It creates as a text node. How do I do it so I simply add HTML without jQuery?

它创建为文本节点。我该怎么做,所以我只是在没有 jQuery 的情况下添加 HTML?

回答by Elliot Bonneville

Close, but no cigar. You have to create the element manually (via createElement), and thenappend it, like this:

关闭,但没有雪茄。您必须手动创建元素(通过createElement),然后附加它,如下所示:

var div = document.createElement("div");
div.innerHTML = "some HTML";
document.getElementsByTagName('body')[0].appendChild(div);

Unfortunately, you can't do this in a one-liner because there's no function to set the innerHTMLproperty of an element, which means it isn't chainable. With a bit of preparation you can make this possible, though:

不幸的是,您不能在单行中执行此操作,因为没有设置innerHTML元素属性的函数,这意味着它不可链接。不过,只要稍作准备,您就可以做到这一点:

function setInnerHTML(element, content) {
    element.innerHTML = content;
    return element;
} 

document.getElementsByTagName('body')[0].appendChild(setInnerHTML(document.createElement("div"), "some HTML"));

回答by Andy

document.createElementrather than createTextNode

document.createElement而不是 createTextNode

回答by Stone Shi

There're a lot of methods:

有很多方法:

elem.innerHTML = ''   // fast
elem.appendChild()    
elem.insertAdjacentElement()  //fast    
elem.insertAdjacentHTML()
elem.insertAdjacentText()

回答by Thielicious

document.body.innerHTML+=document.createElement('div').outerHTML;