I have the following HTML:
<h3 onclick="replaceNextChild(this);">Some content...</h3>
<div>Div that I am interested in replacing</div>
I have the following JavaScript:
<script>
function replaceNextChild(element) {
element.nextSibling.innerHTML = "I replaced the next element in the DOM";
}
</script>
Why is it that JavaScript does not replace the next element? I am also using jQuery and wouldn't mind a jQuery solution.
Because in many browsers, the nextSibling
will be an empty text node.
Use nextElementSibling
instead.
element.nextElementSibling.innerHTML = "I replaced the next element in the DOM";
You'll need to create a function for browsers that don't support it.
( 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;
}
}
I am using jQuery so any solutions using methods from that library will be helpful too
Well, that changes it just a tad :P
$(this).next().html('I replaced the next element in the DOM');
Because it is a text node. Set nodeValue
or data
instead, if you want to change the text node, otherwise maybe change your function to...
function replaceNextChild(element) {
do {
element = element.nextSibling;
} while (element.nodeType != 1);
element.innerHTML = "I replaced the next element in the DOM";
}
jsFiddle.
But really Patrick's answer (use nextElementSibling
is much better).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With