Finding a table's row by some text it contains in column A, and selecting column B in the same row

StackOverflow https://stackoverflow.com//questions/25000333

  •  20-12-2019
  •  | 
  •  

سؤال

I'm using casperjs. There's a table on the current page, as shown below. I have the string "Title of Row 2 which I like" and I'd like to search for the row in the table which contains this string.

Then click on the button in that row, namely Clicky button 2

<table>
    <!-- ...table header... -->
    <tr id="row1">
        <td>Row 1</td>
        <td>Title of Row 1</td>
        <td>
            <button ... onClick='some javascript function'>Clicky Button 1</button>
        </td>
    </tr>
    <tr id="row 2">
        <td>Row 2</td>
        <td>Title of Row 2 which I like</td>
        <td>
            <button ... onClick='some javascript function'>Clicky button 2</button>
        </td>
    </tr>
</table>

My ideas are:

  1. I made a regular expression to search through the whole DOM for the whole row that has "Title of Row 2 which I like" to get the id of the row it's in. Then with this I composed a selector, and found the button under that row. I've done this and it's fine.

And that's about it for my ideas. I'm just wondering, is there a more casper (or elegant) way to do this? I had a look at some functions... nothing seems to be able to search for something by its text. Thought something like getElementsAttribute() could get me the id of the row I'm looking for... but there's no way I could find the row.

هل كانت مفيدة؟

المحلول

You can use XPath to achieve this easily. CasperJS provides the XPath utility:

var x = require('casper').selectXPath;

So you click the button like this:

casper.click(x("//tr[contains(td, 'Title of Row 2 which I like')]//button"));

This assumes that there is only one button per row. If the button is in the next td then you could use

casper.click(x("//tr/td[contains(., 'Title of Row 2 which I like')]/following-sibling::td[1]/button"));

نصائح أخرى

JQuery, if you have it available, has a selector that searches for DOM nodes by their text. To match your example above, you could use

$( "td:contains('Title of Row 2 which I like')" )

Note that it's case-sensitive.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top