How can we find the index of columns satisfying below tables ? Some text are in <th>
directly, some are in <a>
tag and some are in <div>
<thead>
<tr>
<th>Text 1</th>
<th>Text 2</th>
<th>Text 3</th>
</tr>
</thead>
//Another table:
<thead>
<tr>
<th>
<a>Text 1</a>
</th>
<th>
<a>Text 2</a>
</th>
</tr>
</thead>
//Another table:
<thead>
<tr>
<th>
<div>Text 1</div>
</th>
<th>
<div>Text 2</div>
</th>
</tr>
</thead>
I have tried below, but this is not complete yet, how can we handle all in single line of code ?
let columnName = "Text 1" ;
const rowText1 = $('#tableID').find('thead').find(`tr:has(a:contains(${columnName}))`).index();
const rowText2 = $('#tableID').find('thead').find(`tr:has(th:contains(${columnName}))`).index();
CodePudding user response:
you can use $('#tableID thead tr th:contains(' columnName ')').index();
it will return the index you are looking for.
Instead of .find()
use jQuery descendant selector that find your tag under all decendents.
here's the JSFiddle.
Notice I have switched column Text 2 in each table and it returns the correct index.
CodePudding user response:
You can omit the selector to search everything with contains
:
$(() => {
const rowText1 = $('#tableID').find('tr:has(:contains("Text 2"))').index();
console.log(rowText1) // Index would be 1
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableID">
<thead>
<tr></tr>
<tr>
<th>Text 1</th>
<th>Text 2</th>
<th>Text 3</th>
</tr>
</thead>
</table>
CodePudding user response:
Consider the following example.
$(function() {
var needle = "Text 1";
var stack = [];
$("table > thead > tr").each(function(i, el) {
$("th", el).each(function(j, cell) {
if ($(cell).text().trim().indexOf(needle) > -1) {
stack.push({
table: i,
col: j
});
}
});
});
console.log("Needles Found", stack);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Text 1</th>
<th>Text 2</th>
<th>Text 3</th>
</tr>
</thead>
</table>
<table>
<thead>
<tr>
<th>
<a>Text 1</a>
</th>
<th>
<a>Text 2</a>
</th>
</tr>
</thead>
</table>
<table>
<thead>
<tr>
<th>
<div>Text 1</div>
</th>
<th>
<div>Text 2</div>
</th>
</tr>
</thead>
</table>
Iterating each table, and each header cell, we can seek out the table and column.