Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get ONLY the items at first level?

Tags:

javascript

xml

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?

like image 519
pizzaboy Avatar asked Dec 15 '16 11:12

pizzaboy


2 Answers

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>
like image 152
rlemon Avatar answered Nov 18 '22 11:11

rlemon


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>
like image 1
Cerbrus Avatar answered Nov 18 '22 10:11

Cerbrus