How To Get The NextSibling After The First NextSibling?
We are able to run this code str.parentNode.nextSibling.tagName and get the name accordingly. What we need is the nextSibling after this nextSibling so we tried this str.parentNod
Solution 1:
childNodes[3]
will return the fourth child of parentNode
, not its second next sibling.
To get that node, you can apply nextSibling
twice:
var tagName = str.parentNode.nextSibling.nextSibling.tagName;
Solution 2:
Note that an element's nextSibling
might be a text node, which doesn't have a tagName property, or may not exist at all, in which case nextSibling
will be undefined
and trying to access its tagName
property will throw an error.
So you likely want do to something like:
var nextSibling = getNextElementSibling(str.parentNode);
var tagName = nextSibling? nextSibling.tagName : ''; // or maybe undefined
if (tagName) {
// do stuff
} else {
// no element sibling was found
}
and the getNextElementSibling
function is something like:
function getNextElementSibling(node) {
while (node && (node = node.nextSibling)) {
if (node.nodeType == 1) {
return node;
}
}
// return undefined
}
Post a Comment for "How To Get The NextSibling After The First NextSibling?"