简体   繁体   中英

Selecting more than one elements where one of the elements is $(this)

How to select an element along with $(this) ?

I know selecting more than one element is possible in jQuery by separating them with a comma(,).

For eg we can select two ids, say "element1" and "element2" as:

$("#element1,#element2")

However, I'm not able to select more than one element if one of them is $(this) , ie I can't select $(this) and $("#element") simultaneously in a single selection. How do I achieve this?

Use .add() to insert more elements

$("#element1, #element2").add(this)

or the other way around

$(this).add("#element1, #element2")

你可以使用.add()

$("#element1,#element2").add(this)

If you select any element in jQuery you create array. Even if you select one element:

var id = jQuery("#my-id");
console.log(id); // [element]

so You can do something like this:

jQuery(document).ready(function(){
    jQuery("a").on("click", function(){
        var allElements = jQuery("div");
        allElements.push(this);
        console.log(allElements)
    });
});

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