Skip to content Skip to sidebar Skip to footer

Check Whether A Class Exists In Any Row Of A Table In JavaScript

I have a table (simplified for this question):


table data table

Solution 1:

function checkExist(){
       var myTr = document.getElementsByTagName('tr');

       for(var i=myTr.length; i--;){
           if(myTr[i].className.match('(^|\\s+)selected(\\s+|$)')){
               alert('true');//return true;
               return;
           }
       }
       alert('false'); //return false
}

and basically attach to a button or link like this:

<table>
    <tr onclick="selectRow">
        <td>table data</td>
        <td>table data</td>
        <td>table data</td>
    </tr>
    <tr class='selected' onclick="selectRow">
        <td>table data</td>
        <td>table data</td>
        <td>table data</td>
    </tr>
</table>
<a href='#' onclick='checkExist()'>click me to find out</a>

Solution 2:

Have you considered using a library? Using jQuery this could be as simple as http://jsfiddle.net/andersand/QAb4s/

My experience is that by using a JS framework makes me not have to worry that much about cross browser compatibility, while also having increased development speed


Solution 3:

Without using an external library, you'd have to do something like the following:

  1. Get all the rows in the table and start looping through them
  2. Check each row's className property for your class (selected).
    • If you're only dealing with the one class, you can just compare:
      tr.className === 'selected'
    • If a row can have more than one class, you'll probably want to use regular expressions. Something like /\bselected\b/
  3. As soon as you get a match, cancel the loop and return true immediately

For extra credit, you could put all of this into a function that takes the class you're looking for and the table in which to look as arguments.

Assignments are due first thing Monday morning.


Post a Comment for "Check Whether A Class Exists In Any Row Of A Table In JavaScript"

Element?

I have a table and I need the cells to have an element posi…