<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.
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.
A couple of issues:
, and
between the two nodes.Try this:
function function1() {
document.getElementById("myNodeOne").parentNode.nextSibling.nextSibling.innerHTML = "asdfsdf";
}
Demo
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";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With