So, I have this xml
<conversation>
<question>
<title>I want to get this parent</title>
<question>
<title>I don´t want to get this one</title>
</question>
<question>
<title>I don´t want to get this one</title>
</question>
</question>
<question>and get this one</question>
<question>and also this one too</question>
</conversation>
and I would like to get the at top level, descending directly from <conversation>
instead of descending from any other tag... How can I get only those 3 <question>
nodes?
document.querySelectorAll('conversation > question')
the > means direct child.
example here just so there is no confusion:
console.log(
document.querySelectorAll('conversation > question')
)
<conversation>
<question>
<title>I want to get this parent</title>
<question>
<title>I don´t want to get this one</title>
</question>
<question>
<title>I don´t want to get this one</title>
</question>
</question>
<question>and get this one</question>
<question>and also this one too</question>
</conversation>
If all you want is the top level <question>
elements, @rlemon's answer is the one you need.
If you want the text from those elements, you'll need to expand his code a little bit:
console.log(
Array.prototype.slice.call( // Convert the `querySelectorAll` result to an array
document.querySelectorAll('conversation > question') // Get all top question nodes
).map(e => e.innerText || e.children[0].textContent) // Get the element's text, or the element's first child's text.
)
<conversation>
<question>
<title>I want to get this parent</title>
<question>
<title>I don´t want to get this one</title>
</question>
<question>
<title>I don´t want to get this one</title>
</question>
</question>
<question>and get this one</question>
<question>and also this one too</question>
</conversation>
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