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 ?
});
The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
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.
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.
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.
$(this).parent().hasClass("a")
or $(this).parent().hasClass("b")
if($(this).parent().hasClass('a'))
And same for b, it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With