I have bunch of elements with class X.
some elements have class Y also (ie both X and Y)
how do I select set of elements only have X with partial class name?
below is my example HTML
<td class="dxeCalendarDay_Office2010Blue dxeCalendarOtherMonth_Office2010Blue" savedcursor="[object Object]" style="cursor: pointer;">29</td>
<td class="dxeCalendarDay_Office2010Blue" savedcursor="[object Object]" style="cursor: pointer;">4</td>
I could select all of them using
By.cssSelector("[class^='dxeCalendarDay']");
The class prefix "_Office2010Blue" will change at run time
But I need to exclude elements which having "dxeCalendarOtherMonth..."
probably something like.....
By.cssSelector("[class^='dxeCalendarDay'].Not:([class*='dxeCalendarOtherMonth'])");
what is the correct syntax?
3 Answers 3
Assume you want to take all the elements having class X
but having no class Y
. Then your code will look like:
By.cssSelector(".x:not(.y)")
For example for the below html:
<div>
<div class="x y">xy</div>
<div class="x y z">xyz</div>
<div class="x z">xz</div>
<div class="x">x</div>
</div>
The mentioned selector will select xz
and x
.
Why not just select:
By.cssSelector('[class="X"]');
This will simply exclude the "Y" class objects without any NOT operators assuming there are NO "Z" class objects in the picture.
-
yeah, simplicity is the keyYu Zhang– Yu Zhang2018年07月23日 09:44:47 +00:00Commented Jul 23, 2018 at 9:44
-
2Matching the class attribute is less robust than matching the class itself.
[class="X"]
would not match the perfectly valid attributesclass="X "
orclass="X Z"
, therefore it’s preferrable to use the built-in class matching:.X
(combined with:not(.Y)
in this case).Martin– Martin2018年07月23日 11:44:14 +00:00Commented Jul 23, 2018 at 11:44 -
Your solution is simple and elegant...but doesn't work with [class ^=X] which would not exclude "Y"1234– 12342018年07月23日 23:19:43 +00:00Commented Jul 23, 2018 at 23:19
The simplest solution is perhaps selecting class X straight away:
By.cssSelector("[class='dxeCalendarDay_Office2010Blue dxeCalendarOtherMonth_Office2010Blue']");
Alternatively, you can go with select a class that ends with syntax:
By.cssSelector("[class$='dxeCalendarOtherMonth_Office2010Blue']");
-
may be I'm not clear....so changed wordings. I need to exclude dxeCalendarOtherMonth1234– 12342018年07月23日 04:50:05 +00:00Commented Jul 23, 2018 at 4:50
Explore related questions
See similar questions with these tags.
(By.cssSelector("[class^='dxeCalendarDay']:not([class*='dxeCalendarOtherMonth'])")