简体   繁体   中英

Select table cells in a column based on the column header text

How can I select the cells in a column based on what text is written in the table column header, eg, "Status", using Javascript or jQuery ?

(Details, not part of the question: I want to later use this to apply background-color to the cells in that column based on the cell content, so that for example 'Error' would get the background-color red and 'Quality OK' would be white.)

Here is a quick fiddle i did for you..

http://jsfiddle.net/N2CHt/2/

HTML

<table>
    <tr>
        <th>One</th>
        <th>Two</th>
        <th>Status</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>Bad</td>
    </tr>
    <tr>
        <td>3</td>
        <td>4</td>
        <td>Good</td>
    </tr>
</table>

JQUERY

$(function(){
    var columnindex = $('th:contains("Status")').index();
    if(columnindex != -1)
    {
        $('tr').each(function(){
            var column = $('td', this).eq(columnindex);

            switch(column.text())
            {
                case "Bad":
                    column.css({ backgroundColor: '#900' });
                    break;

                case "Good":
                    column.css({ backgroundColor: '#090' });
                    break;

                default:

                    break;

            }
        });
    }
});

You can change the colours and what text you are searching for but you should be able to get a gist of whats going on...

Basically we use the contains selector ( https://api.jquery.com/contains-selector/ ) yp find the th that contains the text we are looking for and then .index() ( http://api.jquery.com/index/ ) to get the columns index. We then loop the tr's using .each ( https://api.jquery.com/jQuery.each/ ) and grab the item using eq ( https://api.jquery.com/eq/ ). When then manipulate the css for the td and set its background colour property.

One thing to note is that if 2 column th text contain "Status" you will face problems!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM