不使用jQuery添加到DOM [英] Add to DOM without jQuery
本文介绍了不使用jQuery添加到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这应该很简单,但事实并非如此。
This should be simple, but it's not.
document.getElementsByTagName('body')[0].document.createTextNode( document.createElement('<div>some HTML</div>') );
它创建为文本节点。我该怎么办,所以我只是添加不带jQuery的HTML?
It creates as a text node. How do I do it so I simply add HTML without jQuery?
推荐答案
关闭,但没有雪茄。您必须手动创建元素(通过 createElement
),然后追加它,如下所示:
Close, but no cigar. You have to create the element manually (via createElement
), and then append it, like this:
var div = document.createElement("div");
div.innerHTML = "some HTML";
document.getElementsByTagName('body')[0].appendChild(div);
不幸的是,你不能在单行中执行此操作,因为没有设置<的功能code> innerHTML 元素的属性,这意味着它不可链接。通过一些准备工作,您可以实现这一目标:
Unfortunately, you can't do this in a one-liner because there's no function to set the innerHTML
property of an element, which means it isn't chainable. With a bit of preparation you can make this possible, though:
function setInnerHTML(element, content) {
element.innerHTML = content;
return element;
}
document.getElementsByTagName('body')[0].appendChild(setInnerHTML(document.createElement("div"), "some HTML"));
这篇关于不使用jQuery添加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文