简体   繁体   中英

How to get the first element id in each function jquery

I have a data grid and each row has checkbox with same class name. I need to get the checkbox id. I got the error the object doesn't support.

webpage:

<table>
  <tr><td>
    <span class="chkClass">
        <input name="$ctl02$chk" id="dgrd_ctl02_chk" type="checkbox">
    </span>
  <td/><tr/>
  <tr><td>
    <span class="chkClass">
        <input name="$ctl03$chk" id="dgrd_ctl03_chk" type="checkbox">
    </span>
  <td/><tr/>
</table>

There is my code:

function Selectbox() {
    $('.chkClass).each(function () {
 var chkbox = this.firstChild;
    alert(chkbox.attr('id'));
          });                 

}

It's firstElementChild not firstChild and you should call 'attr' function on $(chkbox) not on chkbox. https://jsfiddle.net/L5r0q4go/

     $('.chkClass').each(function () {
        var chkbox = this.firstElementChild;
        console.log($(chkbox).attr('id'));
     });

     //dgrd_ctl02_chk  
     //dgrd_ctl03_chk

You can also use like this.

$('.chkClass').each(function () {
       alert($(this).find('input:checkbox').attr('id')); 
 }); 

Output:

//dgrd_ctl02_chk  
 //dgrd_ctl03_chk

https://jsfiddle.net/euLatc9o/4/

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