7
<html>
<body>
<script language="JavaScript">
function function1() {
   var m = document.getElementById("myNodeOne").nextSibling;
   m.innerHTML = "asdfsdf";
}
</script>
<p>This PARAGRAPH has two nodes, 
    <b id="myNodeOne">Node One</b>, and 
    <b id="myNodeTwo">Node Two</b>.
</p>
<p></p>
<button onclick="function1();">Node One has a Next Sibling</button>
</body>
</html>

This should print "asdfsdf" in second paragraph tag. But its not working.

Wasim A.
  • 9,660
  • 22
  • 90
  • 120

6 Answers6

16

Try to use nextElementSibling instead of nextSibling

function function1() {
var m = document.getElementById("myNodeOne").nextElementSibling;
m.innerHTML = "asdfsdf";
}

It works because it only fetches HTML elements.

htoniv
  • 1,658
  • 21
  • 40
4

A couple of issues:

  • if you store in the variable m a DOM element and then you set any m property, the DOM will not be affected at all.
  • document.getElementById("myNodeOne").nextSibling is not myNode2, but the text element , and between the two nodes.

Try this:

function function1() {
   document.getElementById("myNodeOne").parentNode.nextSibling.nextSibling.innerHTML = "asdfsdf";
}​

Demo

Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
2

nextSibling returns the node immediately following this node. If there is no such node, it returns null.

Since the immediate following node is a TEXT_NODE, it returns that. Here are all the nodeTypes:

Node.ELEMENT_NODE == 1
Node.ATTRIBUTE_NODE == 2
Node.TEXT_NODE == 3
Node.CDATA_SECTION_NODE == 4
Node.ENTITY_REFERENCE_NODE == 5
Node.ENTITY_NODE == 6
Node.PROCESSING_INSTRUCTION_NODE == 7
Node.COMMENT_NODE == 8
Node.DOCUMENT_NODE == 9
Node.DOCUMENT_TYPE_NODE == 10
Node.DOCUMENT_FRAGMENT_NODE == 11
Node.NOTATION_NODE == 12

Here is an example of how to filter by node type:

function function1() {
   var m = document.getElementById("myNodeOne").nextSibling;

  if (m.nodeType != 1) {
    m = m.nextSibling;
  }
   m.innerHTML = "asdfsdf";
}
istos
  • 2,654
  • 1
  • 17
  • 19
1

This is because next sibling of your first div is text node: , and

Text nodes doesn't have innerHTML attribute

You need to use:

document.getElementById("myNodeOne").nextSibling.nextSibling
antyrat
  • 27,479
  • 9
  • 75
  • 76
1

You have to take into account the text, which is present between your <b>...</b> tags, and is correctly returned as a nextSibling of the first of them

function function1() {
   var m = document.getElementById("myNodeOne");
   m.nextSibling.nextSibling.innerHTML = "asdfsdf";
}

Trogvar
  • 856
  • 6
  • 17
  • It's better if you only provide the part you're updating... otherwise we have to compare every line of your code with the original code to find out what is different! – freefaller Jul 05 '12 at 14:53
1

looks like the next sibling for your myNodeOne is ", and" if you want to get to the next one you'll have to put:

var m = document.getElementById("myNodeOne").nextSibling;
    m.nextSibling.innerHTML= "asdfsdf";
Entrabiter
  • 752
  • 7
  • 13