This is from a section of a much more complicated script. In short, I’m trying to do 2 things here:
- Get an element’s children’s class names, and remove the word “span” from them, then add them to a variable (this works fine).
- Get those class names (in full, with ‘span’ still attached) and add them to an array.
Here’s my code:
var currentSpans = [];
$('container').children().each(function(i2, spans) {
if (spans.className.indexOf('span') != -1) {
total += parseInt(spans.className.replace(/[A-Za-z$-]/g, ""),10);
currentSpans.push(spans.attr('class'));
}
});
It breaks at currentSpans.push(spans.attr('class')); and says #<HTMLDivElement> has no method 'attr'
currentSpans.push(spans.className());
as it was used above, but here it doesn’t work (this was expected though).
What am I doing wrong here? It seems like a simple enough problem but I’m coming up blank, might be because I’ve been working with jquery all day!
spans.attr('class')should be$(spans).attr('class').When you are accessing
spans.classNameyou are using the dom object reference,attr()is not a method of the dom object but a method provided by jQuery so you need to use the jQuery reference to that element by using$(spans).Updated:
Fiddle: