PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 2, 2022

[FIXED] How can you determine if a certain html table header exists using jQuery?

 August 02, 2022     html-table, javascript, jquery     No comments   

Issue

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;

Solution

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');


Answered By - Ram
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing