简体   繁体   中英

How to map html table header cell to a row cell via css or xpath selectors?

So I have data structured like that in page:

<!-- some html-->
<table>
    <thead>
    <tr>
        <th>Date</th><th>Type</th><th>Value</th> <!-- Header I need -->
    </tr>
    </thead>
</table>
<!-- some html-->
<table>
    <tbody>
        <tr id="insertGuidHere">
            <td>eventDate</td><td>eventType</td><td>eventData</td> <!-- Values I need to map -->
        </tr>
    </tbody>
</table>

I have a header row and somewhere down the line in a different table on a different level I have the data row (an overly complex kendo-grid). I can't go from one to another via a reasonable xpath, but I know that indices match correctly.

What I want is a way to map header index to data. Something like reverse nth-child() - I find the element by text and return its index

var x = $x("//th[contains(text(),'Value')]")[0].findIndexAmongSiblings(); // returns 3, because it's 3rd header cell
$("tr#insertGuidHere > td:nth-child(" + x + ")"); // returns eventData cell

I know there is an .index() function in jQuery, but I couldn't get it to run properly, that is to return a numeric.

In the HTML table DOM a cell has a property cellIndex (starts with 0) so you can find the index for XPath with eg x.cellIndex + 1 . Then you can use "id('insertGuidHere')/td[" + (x.cellIndex + 1) + "]" in XPath to select the third cell. That will of course also work with eg //tbody/tr/td[3] to select all third cells of all rows.

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