Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting innerHTML of nextSibling

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.

like image 296
Tono Nam Avatar asked Dec 07 '22 18:12

Tono Nam


2 Answers

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;
    }
}
like image 64
user113716 Avatar answered Dec 10 '22 13:12

user113716


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).

like image 34
alex Avatar answered Dec 10 '22 11:12

alex