2011-12-04 28 views
25

Quiero seleccionar una columna de tabla y todo lo que sé es el texto del encabezado de la columna. (Th.innerText)Cómo seleccionar una columna de tabla con jQuery

probé el siguiente código pero no funciona:

ownerIndex = $('th:contains("Owner")').index(); 
$('table tr td:nth-child(ownerIndex)') 

alguna idea?

Respuesta

43

Ok. He encontrado una solución:

$('table tr td:nth-child('+ownerIndex+')') 
+8

Esto funciona si cada celda tiene colspan = 1, pero se rompe si las celdas tienen diferentes tramos de columna. –

+0

Gracias, he añadido a su idea para establecer el ancho de las columnas para el estilo "table-layout: fixed". En este caso, selecciono niños de colgroup ej. $ ('# plGrid colgroup col: nth-child (0)'). css ('ancho', '150px'); $ ('# plGrid colgroup col: nth-child (1)'). css ('ancho', '250px'); –

+0

make that nth-child (1); enésimo niño (2) –

17

En el ejemplo anterior ownerIndex necesita ser incrementado en 1 para que coincida con la indexación de nth-child, que comienza en 1 en lugar de 0.

Esta es mi opinión: http://jsfiddle.net/2xU8t/

/* Set all the cells in columns with THEHEADING in the heading to red */ 

// Find the heading with the text THEHEADING 
columnTh = $("table th:contains('THEHEADING')"); 

// Get the index & increment by 1 to match nth-child indexing 
columnIndex = columnTh.index() + 1; 

// Set all the elements with that index in a tr red 
$('table tr td:nth-child(' + columnIndex + ')').css("color", "#F00"); 

// Set the heading red too! 
columnTh.css("color", "#F00"); 
Cuestiones relacionadas