maudulus
maudulus

Reputation: 11035

Using a FOR loop for an array of elements selected by class, and calling functions on each

I am attempting to loop over the whateverDivand find the offset of each element. I am getting the error message Uncaught TypeError: undefined is not a function, I suspect because .offset() cannot be called on the element. This brings me to the question of how I can call functions, such as .offset() and .is(":hover") on elements in an array like this.

whateverDiv  = document.getElementsByClassName('whatever')
//RETURNS SOMETHING LIKE [<img src=​"http:​/​/​www.whateversource.jpg">​,<img src=​"http:​/​/​www.whateversource2.jpg">​]
for (i in whateverDiv){
    console.log(whateverDiv[i].offset())
}

Upvotes: 0

Views: 58

Answers (3)

blurfus
blurfus

Reputation: 14031

You could use a jQuery loop:

 $('.whatever').each(function(index, value) {
    console.log('Item: ' + index + ' - element: ' + $(value).text());
   // you could call a function like this on each element:
   // yourFunction($(value));
   // or a function of the jQuery element -> $(value).offset();    
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="whatever">
  item one
</div>
<div class="whatever">
  item two
</div>
<div class="whatever">
  item three
</div>
<div class="whatever">
  item four
</div>
<div class="whatever">
  item five
</div>

Upvotes: 0

krillgar
krillgar

Reputation: 12815

You've coded your loop with a combination of both types of for loop.

for (i in whateverDiv) {
    // 'i' is each element
}

vs.

for (var i = 0; i < whateverDiv.length; i++) {
    // 'i' can be used as an index of the 'whateverDiv' collection
}

However, as has been stated in the comments, your best bet is to use all jQuery, since the objects inside the loop will still need to be converted to a jQuery object to use those functions.

$('.whateverDiv').each(function () {
    console.log($(this).offset());
});

Upvotes: 1

CambridgeMike
CambridgeMike

Reputation: 4622

Assuming you have jquery included

whateverDiv  = document.getElementsByClassName('whatever')
//RETURNS SOMETHING LIKE [<img src=​"http:​/​/​www.whateversource.jpg">​,<img src=​"http:​/​/​www.whateversource2.jpg">​]
for (i in whateverDiv){
    var $div = $(whateverDiv[i])
    console.log($div.offset())
}

And as others mentioned, you shouldn't use for in, but rather the standard for construction. However, if you're using jQuery already you might as well drink the koolaide and use their .each

http://api.jquery.com/each/

$(".whatever").each(function() {
  console.log( $(this).offset() );
});

Upvotes: 1

Related Questions