Wasim A.
Wasim A.

Reputation: 9890

javascript nextsibling function

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

Upvotes: 7

Views: 7365

Answers (6)

htoniv
htoniv

Reputation: 1668

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.

Upvotes: 16

Alberto De Caro
Alberto De Caro

Reputation: 5213

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

Upvotes: 4

istos
istos

Reputation: 2662

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";
}

Upvotes: 2

Entrabiter
Entrabiter

Reputation: 782

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";

Upvotes: 1

Trogvar
Trogvar

Reputation: 856

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";
}

Upvotes: 1

antyrat
antyrat

Reputation: 27765

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

Upvotes: 1

Related Questions