Nishantha
Nishantha

Reputation: 6695

Call each item when multiple selector perform in jQuery

I want to set each of the checkbox's .parent("span").prop("title") to their .parent("span").parent("td").parent("tr")'s title. Because of jQuery iteratively perform when there are multiple elements, can't I do something like this without a loop?

$(":checkbox").parent("span").parent("td").parent("tr").prop("title", $(this).parent("span").prop("title"));

Rendered in browser something like this.

<tr class="GridRow_Default" id="ctl00_body_grdTime_ctl00__2">
    <td align="center">
        <span title="Regularizable">
            <input id="ctl00_body_grdTime_ctl00_ctl07_chkSub" type="checkbox" name="ctl00$body$grdTime$ctl00$ctl07$chkSub">
        </span>
    </td>       
</tr>

Upvotes: 0

Views: 193

Answers (3)

guest271314
guest271314

Reputation: 1

Try using :has() , .prop(function(propertyName, function) , .closest()

$("span:has(:checkbox)").prop("title", function(index, prop) {
  return $(this).closest("tr").prop("title");
})

Upvotes: 0

Derek
Derek

Reputation: 4751

Use filter() to get just the TRs with SPAN which contain an INPUT:CHECKBOX element, and set the value of the title property of the SPAN to the TR.

$('tr').filter(function() {
    return $(this).find('span > :checkbox').length; 
}).prop('title', function() { return $(this).find('span').eq(0).prop('title'); });

Upvotes: 1

Tushar
Tushar

Reputation: 87203

can't I do something like this without a loop?

NO. To get the current elements reference, you've to iterate over the elements.

You can use each() to iterate over all checkboxes.

$(':checkbox').each(function () {
    // `$(this)` here is the current checkbox

    $(this)
        .closest('tr') // Get closest ancestor `<tr>`
        .attr('title', $(this).parent().attr('title')); // Set attribute value of `title` to that of the `parent`
});

Upvotes: 1

Related Questions