Click here to Skip to main content
15,883,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following HTML elements:
HTML
<p><a href="[someUrl]/about">Text...</a></p>
<p><a href="[someUrl]/info">Text...</a></p>

<p><a href="[someUrl]/blog/1">Text...</a></p>
<p><a href="[someUrl]/blog/2">Text...</a></p>
<p><a href="[someUrl]/blog/3">Text...</a></p>

<p><a href="[someUrl]/blog/4">Text...</a></p>
<p><a href="[someUrl]/contacts">Text...</a></p>

Using CSS, how can I select only the first three elements whose "href" contains the word "blog"?

I can't add class/ids to HTML code.

What I have tried:

CSS
[href*="blog"]:nth-of-type(-n+3) {
  background-color: red;
}

But it selects all the four elements whose "href" contains the word "blog".
Posted

1 solution

According to this :nth-child | CSS-Tricks - CSS-Tricks[^]

looks like this will work

CSS
[href*="blog"]:nth-child(-n+3) {
  background-color: red;
}


[Update]
Went to W3Schools Tryit Editor[^]
and this seems to work
CSS
<!DOCTYPE html>
<html>
<head>
<style>
[href*="blog"]:nth-child(-n+5) {
  background-color: red;
}
a { display: block}
</style>
</head>
<body>

<div>
<a href="[someUrl]/blog/1">Text...</a>
<a href="[someUrl]/about">Text...</a>

<a href="[someUrl]/info">Text...</a>
<a href="[someUrl]/blog/2">Text...</a>
<a href="[someUrl]/blog/3">Text...</a>

<a href="[someUrl]/blog/4">Text...</a>
<a href="[someUrl]/contacts">Text...</a>
</div>
</body>
</html>
 
Share this answer
 
v2
Comments
LB2371 26-Nov-23 8:54am    
That's just what I've already tried, but it selects all the 4 elements whose "href" contains the word "blog" (using Firefox).
M-Badger 26-Nov-23 16:27pm    
Have you tried -n+2 to check that it is not zero based ?
LB2371 26-Nov-23 17:28pm    
That's not the HTML code of my question.
Mike Hankey 26-Nov-23 17:42pm    
If you would have googled the :nth-child or nth-of-type you would have found that they select siblings of a common parent. Your code did not have a common parent so the [href*="blog"] selected all the hrefs with blog as an attribute and ignored the nth part.

My way gave the code a common parent by removing s, the div may not be necessary, you can try it on the site link that I gave you.

If the code has to be exactly as you have it, good luck!
LB2371 26-Nov-23 17:46pm    
The code has to be exactly as I have it - That's the reason of my question here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900