1

I have an XML document like this:

<section>
   <description></description>
   <question>
       <description></description>
   </question>
</section>

I have got the sectionXML stored in a variable called SectionXML. I use:

section.description = SectionXML.getElementsByTagName("description")[0].childNodes[0];

section.description = section.description ? section.description.nodeValue : "";

However, SectionXML.getElementsByTagName("description") returns a list of many descriptions, as if we look many children deeper (great grand children etc) we can see they all have a description, but I just want to get the immediate child of SectionXML with the tag name of "description". How do I do that?

3
  • The code you have should do that, getElementsByTagName returns the elements in DOM order, so the "closest" child will be first. Commented Jan 21, 2015 at 20:25
  • @RobG The OP meant to be there nested description element... Commented Jan 21, 2015 at 20:26
  • 1
    @BhojendraNepal—so you mean "I just want to get the immediate child…" should have been "…immediate children"? Commented Jan 21, 2015 at 22:59

1 Answer 1

1

You may use querySelectorAll():

SectionXML.querySelectorAll("section>description")[0]
// use > to get direct element only
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I got this error: Uncaught SyntaxError: Failed to execute 'querySelectorAll' on 'Element': '>description' is not a valid selector.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.