Pergunta

When I click on a link, I need to find the next <section> that has an ID attribute and return its ID.

So given the following markup and javascript, I would expect clicking on the link to write "section_3" to the console.

<section id="section_1">
    <a href="#" class="findNext">Find</a>
</section>
<section></section>
<section id="section_3"></section>
<section id="section_4"></section>

and

$('a.findNext').click(function() {
    var nextSectionWithId = $(this).closest("section").next("section[id]");
    if (nextSectionWithId) {
        var sectionId = nextSectionWithId.attr('id');
        console.log(sectionId)
    }
});

But this doesn't work. I have set the code up here in jsFiddle.

Any ideas why this is not working?

Foi útil?

Solução

Try :

var nextSectionWithId = $(this).closest("section").nextAll("section[id]:first");

or

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").filter(':first');

Fiddle

You cannot use next because next will look for a match only in the next element. So you can instead use nextAll combined with :first in the selector.

Update

You can use the first() method in jquery to fetch the first element in the collection as well which seems like a faster option.

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").first();

Probably could be this reason:

Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first").

Coutesy @T.J. Crowder

Outras dicas

Use .nextAll()

DEMO

var nextSectionWithId = $(this).closest("section").nextAll("section[id]")[0].id;

DEMO

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").eq(0).attr('id');

DEMO

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").attr('id');
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top