TrySpace
TrySpace

Reputation: 2460

Find first element in Hierarchy, not in children

Ok, two hours later, I can't fix this...

I have:

<section id="sectionmain">
  Section1
 <article data-type="mainarticle" class="page-article" id="home-main">
   <section>
      Section2
     <nav data-parent="home-main" data-type="mainleft" class="page-left">Nav2</nav>
   </section>
  </article>
 <nav data-type="mainleft" class="page-left">
    Nav1
 </nav>
</section>

$("#sectionmain").first().find("[data-type='mainleft']")[0];

See: http://jsfiddle.net/uYZmq/3/

I want to find the first element that is a child of the #sectionmain target, that has the data-type of "mainleft".

As you can see in the fiddle, I have a nested <article> block. which contains a <nav> as well, with the same data-type but I don't want that one, I want the first occurence. But somehow, both firefox and chrome, think the second nested one is the first, which makes no sense. Is there any way around this, and find the REAL first element of the target?

I've tried with .children(), with .closest() and whole load of other combinations, but nothing.

I need it work even when there are more nestings than this.

I just want to search within the id of the element, and then find 'its' <nav>, not its childrens'<nav>. So basically limit the search to one level.

(I need the data-types to be named the same (page-left), it is styled via css. And I don't want to add any additional classes or variables to the elements)

/edit: I don't want [0] to be [1] either, I want code that works regardless of the situation, because if the would have come before the article, it would have worked...

Upvotes: 0

Views: 164

Answers (1)

Christophe
Christophe

Reputation: 28154

first element that is a child of the #sectionmain target, that has the data-type of "mainleft".

document.querySelector("#sectionmain>[data-type='mainleft']")

or with jQuery:

$("#sectionmain>[data-type='mainleft']")[0]

the > sign will restrict the query to the direct children.

Upvotes: 2

Related Questions