简体   繁体   中英

jQuery - find including self

This gives empty output, because console.log is never called. How can i force jQuery to find on all elements, even top level elements?

    $("<div attr></div><div></div>")
       .andSelf()
       .find('[attr]')
       .each(function (index, el) {console.log(el);});

You can use find to find the descendant elements with the said properties using .find('[attr]') then add back the root elements matching the filter using .addBack('[attr]')

$("<div attr></div><div></div>")
    .find('[attr]')
    .addBack('[attr]')
    .each(function (index, el) {
    console.log(el);
});

Demo: Fiddle

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM