Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using .each with closest()

Tags:

jquery

each

I am trying to loop through a bunch of fields in a form and need to change the link text.

My desired result is

Alert("Second 1");
Alert("Second 2");

Example code:

<div class="text-wrapper">
    <input class="field-text" value="">
</div>
<div>
    <ul>
        <li><a href="" class="first">First</li>
        <li><a href="" class="second">Second 1</li>
    </ul>
</div>
<div class="text-wrapper">
    <input class="field-text" value="">
</div>
<div>
    <ul>
        <li><a href="" class="first">First</li>
        <li><a href="" class="second">Second 2</li>
    </ul>
</div>

<script>
jQuery(document).ready(function() {
        jQuery(".text-wrapper").each(function(){
            var value = jQuery(this).closest("a.second").text();
            alert(value);
        });
});
</script>
like image 829
nwkeeley Avatar asked Apr 21 '26 19:04

nwkeeley


1 Answers

closest finds the parent that matches the selector, not the child.

You want find instead.

EDIT: find won't work, as the tag your looking for isn't a child of text-wrapper. You need to manually traverse the DOM to find the element.

jQuery(this).next('div').find("a.second").text();
like image 57
Rocket Hazmat Avatar answered Apr 24 '26 11:04

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!