Ton*_*Nam 3 html javascript jquery dom
我有以下HTML:
<h3 onclick="replaceNextChild(this);">Some content...</h3>
<div>Div that I am interested in replacing</div>
Run Code Online (Sandbox Code Playgroud)
我有以下JavaScript:
<script>
function replaceNextChild(element) {
element.nextSibling.innerHTML = "I replaced the next element in the DOM";
}
</script>
Run Code Online (Sandbox Code Playgroud)
为什么JavaScript不能替换下一个元素?我也在使用jQuery,不介意jQuery解决方案.
因为在许多浏览器中,nextSibling将是一个空文本节点.
element.nextElementSibling.innerHTML = "I replaced the next element in the DOM";
Run Code Online (Sandbox Code Playgroud)
您需要为不支持它的浏览器创建一个函数.
( 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;
}
}
Run Code Online (Sandbox Code Playgroud)