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?
Try :
var nextSectionWithId = $(this).closest("section").nextAll("section[id]:first");
or
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").filter(':first');
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 @TJ Crowder
Use .nextAll()
var nextSectionWithId = $(this).closest("section").nextAll("section[id]")[0].id;
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").eq(0).attr('id');
var nextSectionWithId = $(this).closest("section").nextAll("section[id]").attr('id');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.