javascript - How can you determine if a certain html table header exists using jQuery? - Stack Overflow

Let's say I have the following table:<table id="mytable"><thead><tr>&

Let's say I have the following table:

<table id="mytable">
<thead>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 4</th>
  </tr>
</thead>
<tbody>
    <td>1</td>
    <td>2</td>
    <td>3</td>
</tbody>

and I want to see if it has a certain column based on if there is a "th" with that text? Is there a way to have a "HasColumn" method like this below?

  var hasCol = HasColumn("#mytable", "Col 1");
  //hasCol = true;

  var hasCol = HasColumn("#mytable", "Col 50");
  //hasCol = false;

Let's say I have the following table:

<table id="mytable">
<thead>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 4</th>
  </tr>
</thead>
<tbody>
    <td>1</td>
    <td>2</td>
    <td>3</td>
</tbody>

and I want to see if it has a certain column based on if there is a "th" with that text? Is there a way to have a "HasColumn" method like this below?

  var hasCol = HasColumn("#mytable", "Col 1");
  //hasCol = true;

  var hasCol = HasColumn("#mytable", "Col 50");
  //hasCol = false;
Share Improve this question edited Jul 18, 2018 at 8:59 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 25, 2015 at 22:07 leoraleora 197k368 gold badges907 silver badges1.4k bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You could use the :contains selector but it doesn't use the exact match criterion, i.e. if you pass Col 1 to the selector and one of the elements has Col 12 text content then it will select that element as it contains the specified text. I'd use the filter method:

var hasColumn = $('#mytable thead th').filter(function() {
   return this.textContent === 'Col 1';
}).length > 0;

Here is a vanilla JavaScript alternative:

function hasColumn(tblSel, content) {
    var ths = document.querySelectorAll(tblSel + ' th');
    return Array.prototype.some.call(ths, function(el) {
         return el.textContent === content;
    });
};

var hasCol = hasColumn('#mytable', 'Col 1');

Use :contains()

    console.log($('#mytable th:contains(Col 1)').length);
    console.log($('#mytable th:contains(Col 50)').length);
<script src="https://ajax.googleapis./ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table id="mytable">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 4</th>
    </tr>
  </thead>
  <tbody>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tbody>

function HasColumn(selector,text){
    return $(selector +' th:contains('+text+')').length > 0;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744870135a4598210.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信