Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery each and attr functions

I have this html:

<input id="testme" test="something"/><label test="something2"></label>

and this js

$("[test]").each(alert($(this).attr("test")));

demoed here:

jsfidde

I would think the alert would give me "something" and then "something2". But it does nothing!

What is going on?

like image 280
kralco626 Avatar asked Jan 05 '11 15:01

kralco626


People also ask

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can we use foreach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

How each loop works in jQuery?

each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.

How do you iterate in jQuery?

. each() is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback.


2 Answers

You are alerting the wrong thing. The each simply returns the collection/jQuery. You would need to alert inside the each callback to alert the values of the custom attribute. Also. Please use the data- prefix when assigning [custom attributes][1] for better standards compliance.

$(".classname").each(function(){
    alert($(this).attr("classname"));
});
like image 190
Josiah Ruddell Avatar answered Oct 12 '22 14:10

Josiah Ruddell


.each() takes a function, it should look like this instead:

$("[test]").each(function() {
  alert($(this).attr("test"));
});

You can test it out here.

like image 41
Nick Craver Avatar answered Oct 12 '22 13:10

Nick Craver