user571099
user571099

Reputation: 1511

is there a proper way to iterate over multiple selectors in jquery

suppose i have a .on() function wherein i select multiple ids

    $("#i, #am, #your, #father").on("click" , function(event){
    //iterate over the selectors and return tagname
       alert ( $("#i").prop("tagName")  );
       alert ( $("#am").prop("tagName") );
       alert ( $("#your").prop("tagName") );
       alert ( $("#father").prop("tagName") );
    }

the only method that i can think of is to alert each one separately. is there a known method for handing the $("#i, #am, #your, #father") as a sort of array?

Upvotes: 2

Views: 1637

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196286

Something like this ?

var $groupSelection = $('#i, #am, #your, #father');

$groupSelection.on('click', function(e){
   $groupSelection.each(function(){
      alert( $(this).prop('tagName') );
   });
});

Demo at http://jsfiddle.net/ZHpFa/

Upvotes: 2

Tats_innit
Tats_innit

Reputation: 34117

Try this please:

Interesting read: jQuery: What's the difference between '$(this)' and 'this'?

Also on click of any of these chained ids you can use $(this) to get prop tagName

Further if you are wondering how to bind all of them to on var see here: $foo example: http://jsfiddle.net/6hwLS/5/

Hope this helps,

$("#i, #am, #your, #father").on("click" , function(event){
//iterate over the selectors and return tagname
   alert($(this).prop("tagName")  );

}

further you can also do this

var $foo = $("#i, #am, #your, #father");

$foo.on("click", function(event) {
    //iterate over the selectors and return tagname
    alert($(this).prop("tagName"));

}​

Upvotes: 4

Related Questions