开发者

Check whether a class exists in any row of a table in JavaScript

开发者 https://www.devze.com 2023-02-12 10:50 出处:网络
I have a table (simplified for this question): <table><br> <tr onclick=\"selectRow\"><br>

I have a table (simplified for this question):

<table><br>
  <tr onclick="selectRow"><br>
    <td>table data</td><br>
    <td>table data</td><br>
    <td>table data</td><br>
  </tr><br>
  <tr class="selected" on开发者_开发知识库click="selectRow"><br>
    <td>table data</td><br>
    <td>table data</td><br>
    <td>table data</td><br>
  </tr><br>
</table>

class="selected" is a result of clicking on the row. I want to make a button that when clicked, would return true if there is a row with the class 'selected', and false if there is not.

Any help is greatly appreciated.


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>


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号