views:

1020

answers:

2

How can I count the number of elements that match my CSS selector??

I am trying to use SeleniumRC to test my GWT App and am trying to match elements using CSS selectors.

I want to count the number of enabled Buttons in the following HTML.

A button is enabled if it is under a td with class="x-panel-btn-td " and disabled if it is under a td with class="x-panel-btn-td x-hide-offsets"

So basically, I want to retrieve count of Buttons under TD x-panel-btn-td

<table cellspacing="0">
    <tbody>
    <tr>
        <td id="ext-gen3504" class="x-panel-btn-td ">
            <em unselectable="on">
                <button id="ext-gen3506" class="x-btn-text" type="button">OK</button>
            </em>
        </td>
        <td id="ext-gen3512" class="x-panel-btn-td x-hide-offsets">
            <em unselectable="on">
                <button id="ext-gen3506" class="x-btn-text" type="button">Yes</button>
            </em>
        </td>
        <td id="ext-gen3520" class="x-panel-btn-td">
            <em unselectable="on">
                <button id="ext-gen3506" class="x-btn-text" type="button">No</button>
            </em>
        </td>
        <td id="ext-gen3528" class="x-panel-btn-td x-hide-offsets">
            <em unselectable="on">
                <button id="ext-gen3506" class="x-btn-text" type="button">Cancel</button>
            </em>
        </td>
    </tr>
    </tbody>
</table>
+2  A: 

This should be relatively simple. You can do it multiple ways but I would suggest using the getEval(...) in DefaultSelenium.

Write some javascript that:

1) gets all elements by id: ext-gen3506 2) iterates through all elements and checks to see if it's enabled 2.5) if it's enabled, increment a count 3) "return" the count.

Generally, getEval(...) will return the value of the last statement that ran...so that should give you the count.

vinnybad
the buttons wouldnt have same id... (i copy pasted tht button tag and hence the same id displayed in the code snippet. my bad.)I should get all elements of type button.
Nirmal Patel
+2  A: 

As far as I am aware you can't do this using CSS selectors, but there is a command in Selenium for counting by XPath. The following command will verify there are two disabled buttons:

verifyXpathCount | //td[contains(@class, 'x-hide-offsets')]//button | 2

In Selenium RC (Java) this would look more like

assertEquals(selenium.getXpathCount("//td[contains(@class, 'x-hide-offsets')]//button"), 2);
Dave Hunt
Accepting this as answer because this is more straight forward in selenium terms.
Nirmal Patel