简体   繁体   中英

iterating through array of class elements and selecting sibling in jquery

I have a structure in html like

 <div class="combo-wrapper" tabindex="0" style="display: inline-block; width: 120px; height: 23px;">
<div class="combo-button" style="width: 20px; height: 23px; display: inline-block;"></div>
<div class="combo-selected" style="width: 100px; height: 23px; display: inline-block;">Pending For Upload L2-GM</div>
</div>

In its sibling i have a dropdown

<select class="bydd">
<option value="">Select</option>
<option value="H">Hold</option>
<option value="D">Delete</option>
</select>

When i tried to set title

$(".combo-wrapper").each(function (i) {

        $('.combo-wrapper')[i].attr("title", $('.combo-wrapper')[i].siblings(".bydd option:selected").text());

    });

it throws undefined error

$('.combo-wrapper')[0].siblings() itself throws not a function error in console

When you retrieve a value from a jQuery object by index you're actually getting the underlying DOMElement not a jQuery object, hence the undefined function error when attempting to get the attr .

To get a jQuery object by index you need to use the eq() method:

$('.combo-wrapper').eq(i).attr("title", $('.combo-wrapper').eq(i).siblings(".bydd option:selected").text());

Or you can use the :eq selector:

$('.combo-wrapper:eq(' + i + ')').attr("title", $('.combo-wrapper:eq(' + i + ')').siblings(".bydd option:selected").text());

because $('.combo-wrapper')[0] returns a dom element reference which does not have jQuery related methods.

You can use this (it is again a dom element reference not a jQuery wrapper) to refer to the current element in the each loop, and then wrap it in jQuery to use jQuery method on it

$(".combo-wrapper").each(function (i) {

    $(this).attr("title", $(this).siblings(".bydd").find("option:selected").text());

});

Another way is

$(".combo-wrapper").attr("title", function () {
    return $(this).siblings(".bydd").find("option:selected").text()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM