我有以下HTML:
<h3 onclick="replaceNextChild(this);">Some content...</h3>
<div>Div that I am interested in replacing</div>我有以下JavaScript:
<script>
function replaceNextChild(element) {
element.nextSibling.innerHTML = "I replaced the next element in the DOM";
}
</script>为什么JavaScript不替换下一个元素呢?我也在使用jQuery,不介意使用jQuery解决方案。
发布于 2011-10-17 09:14:18
因为在许多浏览器中,nextSibling将是一个空的文本节点。
element.nextElementSibling.innerHTML = "I replaced the next element in the DOM";您需要为不支持它的浏览器创建一个函数。
( element.nextElementSibling || nextElementSibling( element ) )
.innerHTML = "I replaced the next element in the DOM";
function nextElementSibling( el ) {
if( el ) {
while( (el = el.nextSibling) && el.nextSibling.nodeType !== 1 );
return el;
}
}发布于 2011-10-17 09:14:09
我使用的是jQuery,所以任何使用该库中的方法的解决方案都会很有帮助
好吧,这只是稍微改变了一下:P
$(this).next().html('I replaced the next element in the DOM');因为它是一个文本节点。如果您想更改文本节点,请改为设置nodeValue或data,否则可能会将您的函数更改为...
function replaceNextChild(element) {
do {
element = element.nextSibling;
} while (element.nodeType != 1);
element.innerHTML = "I replaced the next element in the DOM";
}jsFiddle。
但实际上是Patrick's answer (使用nextElementSibling要好得多)。
发布于 2015-05-07 15:34:33
nextSibling属性返回同一树级别中紧跟在指定节点后面的节点。
返回的节点作为node对象返回。
此属性与nextElementSibling之间的区别在于,nextSibling将下一个同级节点作为元素节点、文本节点或注释节点返回,而nextElementSibling将下一个同级节点作为元素节点返回(忽略文本和注释节点)。
此属性为只读。
http://www.w3schools.com/jsref/prop_node_nextsibling.asp
https://stackoverflow.com/questions/7788529
复制相似问题