jQuery- How to select a element with class name from a list of elements

2k views Asked by At

I am using jQuery.

I want to select a cell from a table. So I tried the following codes.

 // First line works fine for me. I can get a list of columns at the correct target row.
 var targetColumns = $(elemClicked).closest("tr").find("td"); 

 // I want to get the cell with the class named "draftstatus". This line has problem. I cannot get what I want.
 var targetCell = columnsAtTargetRow.$(".draftstatus");

The targetColumns inspected from browser looks like the following: enter image description here

The 5th td above is my target cell.

I also try to use find() function. It won't work either because find() will start from next children level.

     columnsAtTargetRow.find(".draftstatus"); // this does not work.

What functions should I used to get that cell within that "list of td".

Thanks in advance.

2

There are 2 answers

0
abbottmw On BEST ANSWER

You just need to figure out which selectors to use.

var targetColumns = $(elemClicked).closest("tr").find("td"); 

this goes up the DOM to the "tr" and selects the tds. If the elemClicked is inside a td you can select the tds with closest("td"), and then use siblings(".draftstatus");

If the elemClicked is a td, then you can just use siblings(".draftstatus");

Here is some example code to help demonstrate some selectors. Hope this helps some and not confused you more.

$(function(){
    
    
    //reference all cells with myclass class using filter
    $("#table1 tbody td").filter(".myclass").addClass("red");

    // click events for all tds reference the .target class cell using siblings
    $("#table1 tbody td").on("click",function(e){
        $(this).siblings(".target").toggleClass("red");
    }); 
    
  
  //items inside a table cell click event
    $("#table1 tbody td a").on("click",function(e){
      //toggle bold class
        $(this).closest("td").siblings(".target").toggleClass("bold");
          //prevent event from bubbling up 
          e.stopPropagation();
    }); 
})
.red {
    background-color:red;
}

.bold { font-weight:bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<table border="1" id="table1">
    <tbody>
        <tr>
            <td>foo</td>
            <td>bar</td>
            <td class="myclass target">value2</td>
            <td>Two <a href="#">link</a></td>
        </tr>
      
       <tr>
            <td>foo</td>
            <td>bar</td>
            <td class="myclass target">value2</td>
            <td>Two <a href="#">link</a></td>
        </tr>
      
    </tbody>
</table>

1
Bhojendra Rauniyar On

This is incorrect:

columnsAtTargetRow.$(".myclass");

This should be:

columnsAtTargetRow.find(".myclass");