¿Cómo podemos encontrar el índice de las columnas que satisfacen las siguientes tablas? Algunos textos están en <th> directamente, algunos están en la etiqueta <a> y otros están en <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>Lo intenté a continuación, pero aún no está completo, ¿cómo podemos manejar todo en una sola línea de código?
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();puede usar $('#tableID thead tr th:contains('+columnName+')').index(); devolverá el índice que está buscando.
En lugar de .find() use el selector de descendientes jQuery que encuentra su etiqueta debajo de todos los descendientes.
aquí está el JSFiddle .
Observe que he cambiado la columna Texto 2 en cada tabla y devuelve el índice correcto.
Puede omitir el selector para buscar todo lo que 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>Considere el siguiente ejemplo.
$(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>Al iterar cada tabla y cada celda de encabezado, podemos buscar la tabla y la columna.