5

I have following code. As you can see, all my div elements has same class name. I want to select 3rd div element by CSS selector. I couldn't find any way. nth-child(n) is used for sub-element(child). Any idea?

<div class="linkDisplayStyle"> <a href="#1"> </div>
<div class="linkDisplayStyle"> <a href="#2"> </div>
<div class="linkDisplayStyle"> <a href="#3"> </div>
<div class="linkDisplayStyle"> <a href="#4"> </div>
<div class="linkDisplayStyle"> <a href="#5"> </div>
<div class="linkDisplayStyle"> <a href="#6"> </div>
2
  • Each element within the html document except the html element itself has a parent node. Commented Sep 19, 2015 at 16:03
  • By.cssSelector(".linkDisplayStyle:nth-of-type(2)") should help you. nth-of-type is a 0 based index so giving in 2 would return the 3rd element. Commented Sep 19, 2015 at 16:42

2 Answers 2

3

nth-child works when you look for child under a parent node. To show you an example I came up with the following

.parent>div:nth-child(3)

Html

<div class="parent"> 
    <div class="linkDisplayStyle"> <a href="#1"> </div>
    <div class="linkDisplayStyle"> <a href="#2"> </div>
    <div class="linkDisplayStyle"> <a href="#3"> </div>
    <div class="linkDisplayStyle"> <a href="#4"> </div>
    <div class="linkDisplayStyle"> <a href="#5"> </div>
    <div class="linkDisplayStyle"> <a href="#6"> </div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

You can use nth-child(3) to select 3rd element. You can also use nth-of-type(3).

.linkDisplayStyle {
  width: 50px;
  height: 50px;
  margin: 5px;
  background: red;
  float: left;
  line-height: 50px;
  text-align: center;
  font-size: 25px;
}
.linkDisplayStyle:nth-of-type(3) {
  background: green;
}
.linkDisplayStyle a {
  color: white;
  text-decoration: none;
}
<div class="linkDisplayStyle">
  <a href="#1">1</a>
</div>
<div class="linkDisplayStyle">
  <a href="#2">2</a>
</div>
<div class="linkDisplayStyle">
  <a href="#3">3</a>
</div>
<div class="linkDisplayStyle">
  <a href="#4">4</a>
</div>
<div class="linkDisplayStyle">
  <a href="#5">5</a>
</div>
<div class="linkDisplayStyle">
  <a href="#6">6</a>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.