Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: iterate over nested elements using each

i have this basic html structure:

<div class=a>
  <div class=m></div>
  <div class=m></div>
</div>
<div class=b>
  <div class=m></div>
  <div class=m></div>
</div>

now i want to iterate over all m's but also would like to know if i am in a or b. using basic jquery syntax each i fail to do find this out.

$('.m').each(function(index) {
    // how do i know if this m is part of a or b ?
});
like image 409
clamp Avatar asked Aug 26 '11 14:08

clamp


People also ask

What is each() in jQuery?

The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

How to loop through HTML elements using jQuery?

Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.

How to iterate Over children jQuery?

jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.

How to loop jQuery function?

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.


2 Answers

$(this).parent().hasClass("a") or $(this).parent().hasClass("b")

like image 149
mark_dj Avatar answered Oct 20 '22 01:10

mark_dj


if($(this).parent().hasClass('a'))

And same for b, it should work.

like image 37
Whiskas Avatar answered Oct 20 '22 00:10

Whiskas