Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 538
Wasim A. Avatar asked Jul 05 '12 14:07

Wasim A.


Video Answer


4 Answers

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.

like image 83
htoniv Avatar answered Sep 21 '22 17:09

htoniv


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

like image 44
Alberto De Caro Avatar answered Sep 22 '22 17:09

Alberto De Caro


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";
}
like image 36
istos Avatar answered Sep 24 '22 17:09

istos


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
like image 24
antyrat Avatar answered Sep 23 '22 17:09

antyrat