Lokesh
Lokesh

Reputation: 1

how to write customizes css to get single webelement out of multiple matched webelements

I have a cssSelector which is div.formErrorContent but with this there are 4 matched elements out of 4 I need to locate 1st element. Can any one help me ?

I know how to write xpath for the same as :

(//div[@class='formErrorContent'])[1]

But I want css locator.

Upvotes: 0

Views: 60

Answers (1)

Mihai T
Mihai T

Reputation: 17697

without any html structure provided by you, i made 2 simple examples.

A. selecting with :first-child selector or :nth-child works only if the 4 divs with same class are all children of the same container, and are the only ones inside that container

see code snippet below

#wrapper {
  background:blue
}
.formErrorContent{
  height:100px;
  background:red;
  width:100px;
}
.formErrorContent:first-child {
  background:green;
}
.formErrorContent:nth-child(2) {
  background:yellow;
}
.formErrorContent:nth-child(3) {
  background:white;
}
.formErrorContent:last-child {
  background:black;
}
<div id="wrapper">
<div class="formErrorContent">

</div>
<div class="formErrorContent">

</div>
<div class="formErrorContent">

</div>
<div class="formErrorContent">

</div>
</div>

B. or if you have more elements in that container, you can select the first div with that class depending on what element you have before it ( CSS = cascading style sheet so you can select only from top to bottom of the HTML structure, not the other way )

for example if you have a p element before .formErrorContent you should use the sibling connector + like so

p + .formErrorContent { background:green }

see snippet below :

#wrapper {
  background:blue
}
p { 
color:white
}

.formErrorContent{
  height:100px;
  background:red;
  width:100px;
}
p + .formErrorContent { 
background:green;
}
<div id="wrapper">
<p>
This is a p element sibling of the other divs in this container
</p>
<div class="formErrorContent">

</div>
<div class="formErrorContent">

</div>
<div class="formErrorContent">

</div>
<div class="formErrorContent">

</div>
</div>

what i want to point out is that there are a number of ways to achieve what you want, but it depends on the html structure

Upvotes: 1

Related Questions