0

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...

4

1 回答 1

2

#sectionmain 目标的子元素的第一个元素,其数据类型为“mainleft”。

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

或使用 jQuery:

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

>标志会将查询限制为直接子级。

于 2013-10-19T15:32:23.127 回答