CSS selector that excludes some child elements

Viewed 308

I have this HTML:

<div class="item-cost">
    <a data-passage="Shop" class="link-internal macro-link" tabindex="0" id="Link1">$10 <sup>1</sup></a>
</div>

I am writing this testcafe code to get the cost:

.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1')

This fails because the inner text is $11, not $1. The reason it's failing is because the contents of the sup element are included in the inner text. Is there any way I can modify the selector above so that it gives me the inner text without including the sup element? I cannot modify the HTML.

3 Answers

How about using <sup> in your test too?

.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1 ' + Selector('.item-cost sup').nth(0).innerText)

Instead of using innerText, use innerHTML and then use a regexp to remove the trailing <sup>...</sup> (including the space before <sup>):

.expect(Selector('.item-cost').nth(0).innerHTML.replace(/ <sup>.*<\/sup>$/, ''))
.eql('$1')

That will give you just the $10.

I hesitate to add my 2 cents to this discussion as I just happened to stumble into it and am not really familiar with testcafe. But those 2 cents are too long for a comment, so I figure I'll post it as a possible answer and you make of it what you will.

It seems to me that what you are trying to do is select the text of the <a> node while at the same time excluding that of its <sup> child node. An operation like that is easily achieved by using an xpath expression like:

//div/a/text()

Unfortunately, testcafe doesn't seem to support xpath and there is no intention to do it in the future. The main reason seems to be the existence of utilities that can convert xpath to css selectors for use with testcafe.

Unfortunately again, xpath and css selctors aren't equivalent and there are things you can do with xpath that cannot (currently) be done with css selectors. And this case is probably one of them.

To the rescue may comes this utility for adding xpath support to testcafe. So I would try using that with the xpath expression above and see if it works for you. If not, no harm done, I guess.

Related