Javascript - 没有innerHTML的div内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7822183/
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
Javascript - div content without innerHTML
提问by Kedor
I wanted to ask how to change div content, but not using innerhtml.
我想问一下如何更改div内容,但不使用innerhtml。
回答by user113716
DEMO:http://jsfiddle.net/Cb6ME/
演示:http : //jsfiddle.net/Cb6ME/
// get the div
var div = document.getElementById('foo');
// remove child nodes while at least one exists
while( div.childNodes[0] ) {
div.removeChild( div.childNodes[0] );
}
// create a new span element
var span = document.createElement( 'span' );
// give it some text content
span.appendChild( document.createTextNode("I'm new!!!") );
// append the span to the original div
div.appendChild( span );
回答by mjaggard
You can use nodeValue
to access the value of a node, however the value of a div
. In your example you might have the following HTML...
您可以使用nodeValue
来访问节点的值,但是 a 的值div
。在您的示例中,您可能有以下 HTML...
<div id="myLovelyDiv">This is the text that you want to change</div>
and this script...
还有这个剧本...
var myDiv = getElementById("myLovelyDiv");
myDiv.childNodes[0].nodeValue = "The text has been changed.";
but I fail to see why you wouldn't use
但我不明白你为什么不使用
myDiv.innerHTML = "The text has been changed properly.";
回答by JoshHetland
A DIV element is a generic block level (by default) element in HTML used as a structural container to hold one or more block or inline elements.
DIV 元素是 HTML 中的通用块级(默认)元素,用作结构容器来保存一个或多个块或内联元素。
Depending on what it is you want to change you can either select the sub-node in question directly, loop over the childNodes property to find the desired sub-node or completely rewrite the contents as html using innerHTML (which you stated you didn't want to do).
根据您想要更改的内容,您可以直接选择有问题的子节点,循环遍历 childNodes 属性以找到所需的子节点,或者使用 innerHTML 将内容完全重写为 html(您说您没有想要做)。
If you want to add content you can create a new element and use the appendChild(child) method of the DIV element to add to it's contents.
如果您想添加内容,您可以创建一个新元素并使用 DIV 元素的 appendChild(child) 方法添加到其内容中。
Is that what you were looking for?
这就是你要找的吗?