kralco626
kralco626

Reputation: 8624

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?

Upvotes: 10

Views: 40776

Answers (2)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

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"));
});

Upvotes: 21

Nick Craver
Nick Craver

Reputation: 630389

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

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

You can test it out here.

Upvotes: 3

Related Questions