Ininter Ininter - 6 days ago 7
Javascript Question

Extract text of paragraph using nextSibling

How can I extract a text of paragraph using

nextSibling
on this paragraph? I tried many variants, e.g.
nextSibling.nodeValue
or
nextSibling.textContent
but none of them work.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload = function() {
var a = document.getElementById("p1");
var b = a.nextSibling.nodeValue;
console.log(b);
}
</script>
</head>
<body>
<p id="p1">
Some text
</p>
</body>
</html>

Answer

Text nodes in JavaScript are children of their DOM tag. So, instead of sibling, use a child selector: a.firstChild will do what you want.

Comments