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 the second paragraph. But it does not work.
Try using nextElementSibling instead of nextSibling
function function1() { var m = document.getElementById("myNodeOne").nextElementSibling; m.innerHTML = "asdfsdf"; } This works because it only extracts HTML elements.
A few problems:
- if you store the DOM element in the variable m, and then you set any value of the m property, the DOM will not be affected at all.
- document.getElementById ("myNodeOne"). nextSibling is not myNode2, but a text element
, andbetween two nodes.
Try the following:
function function1() { document.getElementById("myNodeOne").parentNode.nextSibling.nextSibling.innerHTML = "asdfsdf"; }β NextSibling returns a node immediately after that node. If there is no such node, it returns null.
Since the next next node is TEXT_NODE, it returns this. 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 The following is an example of filtering using a node type:
function function1() { var m = document.getElementById("myNodeOne").nextSibling; if (m.nodeType != 1) { m = m.nextSibling; } m.innerHTML = "asdfsdf"; } This is because the next brother of your first div is the text node:, , and
Text nodes do not have an innerHTML attribute
You need to use:
document.getElementById("myNodeOne").nextSibling.nextSibling You must consider the text that is present between your <b>...</b> tags and returns correctly as the next
function function1() { var m = document.getElementById("myNodeOne"); m.nextSibling.nextSibling.innerHTML = "asdfsdf"; } similar to the next brother for your myNodeOne ", and" if you want to go to the next, you have to put:
var m = document.getElementById("myNodeOne").nextSibling; m.nextSibling.innerHTML= "asdfsdf";