Reputation: 640
<ol>
<li>Text</li>
<li>Text</li>
<li><a href="#"> Hyper Text 1</a></li>
<li><a href="#"> Hyper Text 2</a></li>
<li>Text</li>
</ol>
I want to apply css on second anchor tag(Hyper Text 2) only. I wanna do it with css only if possible. I searched a lot but couldn't figured out how to do this.
Update: I don't know how many more li will be added in list in future. I don't wanna ended up by change nth-item(no.) again and again. That's why putting nth-child only on li won't help. But I am certin that li with anchor tag will only be 2.
Upvotes: 1
Views: 1144
Reputation: 6524
Please note: This answer presents a possible solution to the OP's specific problem which was clarified in a comment and does not necessarily address the problem in title of the question "How to apply css on anchor tag of nth list item?".
If you ...
... then you might want to use CSS attribute selectors.
Having this HTML specifying the menu:
<ol class="some-menu">
<li>Text</li>
<li>Text</li>
<li><a href="http://url_abc#"> Hyper Text 1</a></li>
<li><a href="http://url_def#"> Hyper Text 2</a></li>
<li>Text</li>
</ol>
... you can select the specific element with CSS based on that element's attribute value:
ol.some-menu li a[href*="url_def"] {
outline: 5px solid red;
}
This selector selects all <a>
elements that have a href
value containing url_def
- that are also inside <li>
s, which are inside <ul class="some-menu">
elements.
Working example: https://codepen.io/anon/pen/jxWmxR.
Attribute selectors do have a few modi operandi available and are well described here: MDN web docs.
Upvotes: 2
Reputation: 619
It is not possible with css only...one thing you can do is Simply add class to that 2nd anchor tag..and here you go..
.Changecolor{
color:green;
}
<ol>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li><a href="#"> Hyper Text 1</a></li>
<li><a href="#" class="Changecolor"> Hyper Text 2</a></li>
<li>Text</li>
</ol>
Upvotes: 0
Reputation: 12058
You can do it with a little bit of jQuery:
$('li:has(a) a').last().css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li><a href="#">Hyper Text 1</a></li>
<li><a href="#">Hyper Text 2</a></li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ol>
Upvotes: 1