1

I have a complex html structure. New to CSS. Want to change my xpath to css as there could be some performance impact in IE

Xpath by firebug: .//*[@id='T_I:3']/span/a

I finetuned to : //div[@id='Overview']/descendant::*[@id='T_I:3']/span/a

Now I need corresponding CSS for the same. Is it possible or not?

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
Venu
  • 353
  • 3
  • 6
  • 18

1 Answers1

1

First of all, I don't think your "finetuning" did the best possible job. An element id should be unique in the document and is therefore usually cached by modern browsers (which means that id lookup is instant). You can help the XPath engine by using the id() function.

Therefore, the XPath expression would be: id('T_I:3')/span/a (yes, that's a valid XPath 1.0 expression).

Anyway, to convert this to CSS, you'd use: #T_I:3 > span > a

Your "finetuned" expression converted would be: div#Overview #T_I:3 > span > a, but seriously, you only need one id selection.

The hashtag # is an id selector.

The space () is a descendant combinator.

The > sign is a child combinator.


EDIT based on a good comment by Fréderic Hamidi:

I don't think #T_I:3 is valid (the colon would be confused with the start of a pseudo-class). You would have to find a way to escape it.

It turns out you also need to escape the underscore. For this, use the techniques mentioned in this SO question: Handling a colon in an element ID in a CSS selector.

The final CSS selector would be:

#T\5FI\3A3 > span > a
Community
  • 1
  • 1
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • 1
    I don't think `#T_I:3` is valid (the colon would be confused with the start of a pseudo-class). You would have to find a way to escape it. – Frédéric Hamidi Sep 05 '13 at 12:49
  • 1
    @FrédéricHamidi Wow. I have been working with XPath and CSS for like five years and I haven't bumped into this. Thank you for learning me something new today! – Petr Janeček Sep 05 '13 at 12:57
  • Thanks Slanec and Frederic. Your inputs are so useful – Venu Sep 05 '13 at 13:58
  • One more small doubt if the id = Refresh-- is same on both div left and right; please suggest on how to deal with it //div[@id='Overview_Left']/descendant::input[@id='Refresh'] – Venu Sep 05 '13 at 14:18
  • @user2742533 That's a clear error in the markup, it's against the spec and should be repaired. If you can't access it, you'll have to stick to your finetuned version for which I provided a conversion to a CSS selector, too. Just don't forget to escape all the needed characters. – Petr Janeček Sep 05 '13 at 14:32
  • 65535-123 > td:nth-of-type(9) > a css selectors should not start with numbers. 65535-123 is an id. I used the below one but it didnt work \65535\-123 > td:nth-of-type(9) > span – Venu Oct 03 '13 at 12:45
  • And I tried the following by including division above it also -- div#One #65535\-123 > td:nth-of-type(9) > span – Venu Oct 03 '13 at 12:53