nwkeeley
nwkeeley

Reputation: 1437

using .each with closest()

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>

Upvotes: 3

Views: 6396

Answers (4)

Harshith J.V.
Harshith J.V.

Reputation: 887

This should work as per test case you provided. You have not closed tag properly which you to have close before trying below code:

$("div:odd").each(function(){
    var value = $(this).find("a.second").html();
    alert(value);
});

Fiddle link: http://jsfiddle.net/harshithjv/2ePn9/1/

Upvotes: 0

Flo
Flo

Reputation: 1965

closest() walks UP the DOM tree starting with the node itself, then it's parentNode, the parentNode's parentNode, and so forth. The function you are looking for is find() which searches the descendants of a given node.

Edit for completeness:

Since a.second is not a descendant of .text-wrapper you will first have to call next(), which returns .text-wrapper's next sibling, i.e. the div element containing a.second.

jQuery(this).next().find('a.second').text()

Upvotes: 3

Chris Dixon
Chris Dixon

Reputation: 9167

Full jsFiddle of the working solution, including both links showing in the console log: http://jsfiddle.net/3rH63/

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227280

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();

Upvotes: 5

Related Questions