I have a bunch of elements with a class name red, but I can't seem to select the first element with the class="red" using the following CSS rule:
.home .red:first-child {
border: 1px solid red;
}
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
What is wrong in this selector and how do I correct it to target the first child with class red?
This is one of the most well-known examples of authors misunderstanding how :first-child works. Introduced in CSS2, the :first-child pseudo-class represents the very first child of its parent. That's it. There's a very common misconception that it picks up whichever child element is the first to match the conditions specified by the rest of the compound selector. Due to the way selectors work (see here for an explanation), that is simply not true.
Selectors level 3 introduces a :first-of-type pseudo-class, which represents the first element among siblings of its element type. This answer explains, with illustrations, the difference between :first-child and :first-of-type. However, as with :first-child, it does not look at any other conditions or attributes. In HTML, the element type is represented by the tag name. In the question, that type is p.
Unfortunately, there is no similar :first-of-class pseudo-class for matching the first child element of a given class. At the time this answer was first posted, the newly published FPWD of Selectors level 4 introduced an :nth-match() pseudo-class, designed around existing selector mechanics as I mentioned in the first paragraph by adding a selector-list argument, through which you can supply the rest of the compound selector to get the desired filtering behavior. In recent years this functionality was subsumed into :nth-child() itself, with the selector list appearing as an optional second argument, to simplify things as well as averting the false impression that :nth-match() matched across the entire document (see the final note below).
While we await cross-browser support (seriously, it's been nearly 10 years, and there has only been a single implementation for the last 5 of those years), one workaround that Lea Verou and I developed independently (she did it first!) is to first apply your desired styles to all your elements with that class:
/*
* Select all .red children of .home, including the first one,
* and give them a border.
*/
.home > .red {
border: 1px solid red;
}
... then "undo" the styles for elements with the class that come after the first one, using the general sibling combinator ~ in an overriding rule:
/*
* Select all but the first .red child of .home,
* and remove the border from the previous rule.
*/
.home > .red ~ .red {
border: none;
}
Now only the first element with class="red" will have a border.
Here's an illustration of how the rules are applied:
.home > .red {
border: 1px solid red;
}
.home > .red ~ .red {
border: none;
}
<div class="home">
<span>blah</span> <!-- [1] -->
<p class="red">first</p> <!-- [2] -->
<p class="red">second</p> <!-- [3] -->
<p class="red">third</p> <!-- [3] -->
<p class="red">fourth</p> <!-- [3] -->
</div>
No rules are applied; no border is rendered.
This element does not have the class red, so it's skipped.
Only the first rule is applied; a red border is rendered.
This element has the class red, but it's not preceded by any elements with the class red in its parent. Thus the second rule is not applied, only the first, and the element keeps its border.
Both rules are applied; no border is rendered.
This element has the class red. It is also preceded by at least one other element with the class red. Thus both rules are applied, and the second border declaration overrides the first, thereby "undoing" it, so to speak.
As a bonus, although it was introduced in Selectors 3, the general sibling combinator is actually pretty well-supported by IE7 and newer, unlike :first-of-type and :nth-of-type() which are only supported by IE9 onward. If you need good browser support, you're in luck.
In fact, the fact that the sibling combinator is the only important component in this technique, and it has such amazing browser support, makes this technique very versatile — you can adapt it for filtering elements by other things, besides class selectors:
You can use this to work around :first-of-type in IE7 and IE8, by simply supplying a type selector instead of a class selector (again, more on its incorrect usage in the question in a later section):
article > p {
/* Apply styles to article > p:first-of-type, which may or may not be :first-child */
}
article > p ~ p {
/* Undo the above styles for every subsequent article > p */
}
You can filter by attribute selectors or any other simple selectors instead of classes.
You can also combine this overriding technique with pseudo-elements even though pseudo-elements technically aren't simple selectors.
Note that in order for this to work, you will need to know in advance what the default styles will be for your other sibling elements so you can override the first rule. Additionally, since this involves overriding rules in CSS, you can't achieve the same thing with a single selector for use with the Selectors API, or Selenium's CSS locators.
On a final note, keep in mind that this answer assumes that the question is looking for any number of first child elements having a given class. There is neither a pseudo-class nor even a generic CSS solution for the nth match of a complex selector across the entire document — whether a solution exists depends heavily on the document structure. jQuery provides :eq(), :first, :last and more for this purpose, but note again that they function very differently from :nth-child() et al. Using the Selectors API, you can either use document.querySelector() to obtain the very first match:
var first = document.querySelector('.home > .red');
Or use document.querySelectorAll() with an indexer to pick any specific match:
var redElements = document.querySelectorAll('.home > .red');
var first = redElements[0];
var second = redElements[1];
// etc
Although the .red:nth-of-type(1) solution in the original accepted answer by Philip Daubmeier works (which was originally written by Martyn but deleted since), it does not behave the way you'd expect it to.
For example, if you only wanted to select the p here:
<p class="red"></p>
<div class="red"></div>
... then you can't use .red:first-of-type (equivalent to .red:nth-of-type(1)), because each element is the first (and only) one of its type (p and div respectively), so both will be matched by the selector.
When the first element of a certain class is also the first of its type, the pseudo-class will work, but this happens only by coincidence. This behavior is demonstrated in Philip's answer. The moment you stick in an element of the same type before this element, the selector will fail. Taking the markup from the question:
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
Applying a rule with .red:first-of-type will work, but once you add another p without the class:
<div class="home">
<span>blah</span>
<p>dummy</p>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
... the selector will immediately fail, because the first .red element is now the second p element.
The :first-child selector is intended, like the name says, to select the first child of a parent tag. So this example will work (Just tried it here):
<body>
<p class="red">first</p>
<div class="red">second</div>
</body>
This won't work, though, if you've nested your tags under different parent tags, or if your tags of class red aren't the first tags under the parent.
Notice also that this doesn't only apply to the first such tag in the whole document, but every time a new parent is wrapped around it, like:
<div>
<p class="red">first</p>
<div class="red">second</div>
</div>
<div>
<p class="red">third</p>
<div class="red">fourth</div>
</div>
first and third will be red then.
For your case, you can use the :nth-of-type selector:
.red:nth-of-type(1)
{
border:5px solid red;
}
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
Credits to Martyn, who deleted his answer containing this approach.
More information about :nth-child() and :nth-of-type() is available at http://www.quirksmode.org/css/nthchild.html.
Be aware that this is a CSS3 selector, therefore some now outdated browser versions may not behave as expected (e.g. IE8 or older). Visit https://caniuse.com/?search=nth-of-type for more details.
The correct answer is:
.red:first-child, :not(.red) + .red { border:5px solid red }
Part I: If element is first to its parent and has class "red", it shall get border.
Part II: If ".red" element is not first to its parent, but is immediately following an element without class ".red", it shall also deserve the honor of said border.
Fiddle or it didn't happen.
Philip Daubmeier's answer, while accepted, is not correct - see attached fiddle.
BoltClock's answer would work, but unnecessarily defines and overwrites styles
(particularly an issue where it otherwise would inherit a different border - you don't want to declare other to border:none)
EDIT:
In the event that you have "red" following non-red several times, each "first" red will get the border. To prevent that, one would need to use BoltClock's answer. See fiddle
The above answers are too complex.
.class:first-of-type { }
This will select the first-type of class. MDN Source
Note: Tested with Chrome 91 and Firefox 89, June 2021.
I am surprised no one mentioned the cleanest solution:
.red:not(.red ~ .red) {
border: 1px solid red;
}
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
you could use first-of-type or nth-of-type(1)
.red {
color: green;
}
/* .red:nth-of-type(1) */
.red:first-of-type {
color: red;
}
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
To match your selector, the element must have a class name of red and must be the first child of its parent.
<div>
<span class="red"></span> <!-- MATCH -->
</div>
<div>
<span>Blah</span>
<p class="red"></p> <!-- NO MATCH -->
</div>
<div>
<span>Blah</span>
<div><p class="red"></p></div> <!-- MATCH -->
</div>
Since the other answers cover what's wrong with it, I'll try the other half, how to fix it. Unfortunately, I don't know that you have a CSS only solution here, at least not that I can think of. There are some other options though....
Assign a first class to the element when you generate it, like this:
<p class="red first"></p>
<div class="red"></div>
CSS:
.first.red {
border:5px solid red;
}
This CSS only matches elements with both first and red classes.
Alternatively, do the same in JavaScript, for example here's what jQuery you would use to do this, using the same CSS as above:
$(".red:first").addClass("first");
I got this one in my project.
div > .b ~ .b:not(:first-child) {
background: none;
}
div > .b {
background: red;
}
<div>
<p class="a">The first paragraph.</p>
<p class="a">The second paragraph.</p>
<p class="b">The third paragraph.</p>
<p class="b">The fourth paragraph.</p>
</div>
I am using below CSS to have a background image for the list ul li
#footer .module:nth-of-type(1)>.menu>li:nth-of-type(1){
background-position: center;
background-image: url(http://monagentvoyagessuperprix.j3.voyagesendirect.com/images/stories/images_monagentvoyagessuperprix/layout/icon-home.png);
background-repeat: no-repeat;
}
<footer id="footer">
<div class="module">
<ul class="menu ">
<li class="level1 item308 active current"></li>
<li> </li>
</ul>
</div>
<div class="module">
<ul class="menu "><li></li>
<li></li>
</ul>
</div>
<div class="module">
<ul class="menu ">
<li></li>
<li></li>
</ul>
</div>
</footer>
According to your updated problem
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
how about
.home span + .red{
border:1px solid red;
}
This will select class home, then the element span and finally all .red elements that are placed immediately after span elements.
Reference: http://www.w3schools.com/cssref/css_selectors.asp
For some reason none of the above answers seemed to be addressing the case of the real first and only first child of the parent.
#element_id > .class_name:first-child
All the above answers will fail if you want to apply the style to only the first class child within this code.
<aside id="element_id">
Content
<div class="class_name">First content that need to be styled</div>
<div class="class_name">
Second content that don't need to be styled
<div>
<div>
<div class="class_name">deep content - no style</div>
<div class="class_name">deep content - no style</div>
<div>
<div class="class_name">deep content - no style</div>
</div>
</div>
</div>
</div>
</aside>
The following code will definitely work well everywhere.
it is simple and short.
<div class="home">
<span>blah</span>
<p class="blue"> first-blue </p>
<p class="blue"> second-blue </p>
<p class="blue"> third-blue </p>
<p class="red"> first-red </p>
<p class="red"> second-red </p>
<p class="red"> third-red </p>
<p class="red"> fourth-red </p>
<p class="pink"> first-pink </p>
<p class="pink"> second-pink </p>
<p class="red"> new-first-red </p>
<p class="red"> new-second-red </p>
</div>
we can select the first-red with:
.home .red:not(.home .red ~ .red) {
background-color: blue;
}
if you want to select new-first-red too you should use + instead of ~.
You could use nth-of-type(1) but be sure that site doesn't need to support IE7 etc, if this is the case use jQuery to add body class then find element via IE7 body class then the element name, then add in the nth-child styling to it.
You can change your code to something like this to get it work
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
This does the job for you
.home span + .red{
border:3px solid green;
}
Here is a CSS reference from SnoopCode about that.
All in All, after reading this all page and other ones and a lot of documentation. Here's the summary:
For first/last child: Safe to use now (Supported by all modern browsers)
:nth-child() Also safe to use now (Supported by all modern browsers). But be careful it even counts siblings! So, the following won't work properly:
/* This should select the first 2 element with class display_class
* but it will NOT WORK Because the nth-child count even siblings
* including the first div skip_class
*/
.display_class:nth-child(-n+2){
background-color:green;
}
<ul>
<li class="skip_class">test 1</li>
<li class="display_class">test 2 should be in green</li>
<li class="display_class">test 3 should be in green</li>
<li class="display_class">test 4</li>
</ul>
Currently, there is a selector :nth-child(-n+2 of .foo) that supports selection by class but not supported by modern browsers so not useful.
So, that leaves us with Javascript solution (we'll fix the example above):
// Here we'll go through the elements with the targeted class
// and add our classmodifer to only the first 2 elements!
[...document.querySelectorAll('.display_class')].forEach((element,index) => {
if (index < 2) element.classList.add('display_class--green');
});
.display_class--green {
background-color:green;
}
<ul>
<li class="skip_class">test 1</li>
<li class="display_class">test 2 should be in green</li>
<li class="display_class">test 3 should be in green</li>
<li class="display_class">test 4</li>
</ul>
A quick 'n dirty jQuery solution for marking first and last element within a group of elements with the same classnames:
$('.my-selector').each(function(index, item) {
if (!$(item).next().hasClass('my-selector')) {
$(item).addClass('last');
}
if (!$(item).prev().hasClass('my-selector')) {
$(item).addClass('first');
}
});
.my-selector {
padding: 5px;
background: #ccc;
}
.my-selector.first {
background: #fcc;
}
.my-selector.last {
background: #cfc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>first element...</span>
<div class="my-selector">Row 1</div>
<div class="my-selector">Row 2</div>
<div class="my-selector">Row 3</div>
<div class="my-selector">Row 4</div>
<span>other elements...</span>
<div class="my-selector">Row 3</div>
<div class="my-selector">Row 4</div>
</div>
Try This Simple and Effective
.home > span + .red{
border:1px solid red;
}
just use
.home > .red ~ .red{
border: 1px solid red;
}
it will work.
I believe that using relative selector + for selecting elements placed immediately after, works here the best (as few suggested before).
It is also possible for this case to use this selector
.home p:first-of-type
but this is element selector not the class one.
Here you have nice list of CSS selectors: https://kolosek.com/css-selectors/
Could you try something like this:
.red:first-of-type {
border: 5px solid red;
}
you also can use this for last element (if you need it):
.red:last-of-type {
border: 5px solid red;
}
Try this solution:
.home p:first-of-type {
border:5px solid red;
width:100%;
display:block;
}
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
CodePen link
I think a lot of people have explained already. your code is selecting only first child of the first instance. If you want to select all the first children of red class, you need to use
.home > .red:first-child {
/* put your styling here */
}
Related
I'm trying to select the first h1 inside a div with a class called detail_container. It works if h1 is the first element within this div, but if it comes after this ul it won't work.
<style type="text/css">
.detail_container h1:first-child
{
color:blue;
}
</style>
</head>
<body>
<div class="detail_container">
<ul>
<li></li>
<li></li>
</ul>
<h1>First H1</h1>
<h1>Second H1</h1>
</div>
</body>
</html>
I was under the impression that the CSS I have will select the first h1 no matter where it is in this div. How can I make it work?
The h1:first-child selector means
Select the first child of its parent
if and only if it's an h1 element.
The :first-child of the container here is the ul, and as such cannot satisfy h1:first-child.
There is CSS3's :first-of-type for your case:
.detail_container h1:first-of-type
{
color: blue;
}
But with browser compatibility woes and whatnot, you're better off giving the first h1 a class, then targeting that class:
.detail_container h1.first
{
color: blue;
}
:first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.
The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.
jQuery's :first selector gives you what you're looking for. You can do this:
$('.detail_container h1:first').css("color", "blue");
For that particular case you can use:
.detail_container > ul + h1{
color: blue;
}
But if you need that same selector on many cases, you should have a class for those, like BoltClock said.
you can also use
.detail_container h1:nth-of-type(1)
By changing the number 1 by any other number you can select any other h1 item.
You could wrap your h1 tags in another div and then the first one would be the first-child. That div doesn't even need styles. It's just a way to segregate those children.
<div class="h1-holder">
<h1>Title 1</h1>
<h1>Title 2</h1>
</div>
Is there a way to select every nth child that matches (or does not match) an arbitrary selector? For example, I want to select every odd table row, but within a subset of the rows:
table.myClass tr.row:nth-child(odd) {
...
}
<table class="myClass">
<tr>
<td>Row
<tr class="row"> <!-- I want this -->
<td>Row
<tr class="row">
<td>Row
<tr class="row"> <!-- And this -->
<td>Row
</table>
But :nth-child() just seems to count all the tr elements regardless of whether or not they're of the "row" class, so I end up with the one even "row" element instead of the two I'm looking for. The same thing happens with :nth-of-type().
Can someone explain why?
This is a very common problem that arises due to a misunderstanding of how :nth-child(An+B) and :nth-of-type() work.
In Selectors Level 3, the :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector.
Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type, which refers to the tag name in HTML, and not the rest of the selector.
This also means that if all the children of the same parent are of the same element type, for example in the case of a table body whose only children are tr elements or a list element whose only children are li elements, then :nth-child() and :nth-of-type() will behave identically, i.e. for every value of An+B, :nth-child(An+B) and :nth-of-type(An+B) will match the same set of elements.
In fact, all simple selectors in a given compound selector, including pseudo-classes such as :nth-child() and :not(), work independently of one another, rather than looking at the subset of elements that are matched by the rest of the selector.
This also implies that there is no notion of order among simple selectors within each individual compound selector1, which means for example the following two selectors are equivalent:
table.myClass tr.row:nth-child(odd)
table.myClass tr:nth-child(odd).row
Translated to English, they both mean:
Select any tr element that matches all of the following independent conditions:
it is an odd-numbered child of its parent;
it has the class "row"; and
it is a descendant of a table element that has the class "myClass".
(you'll notice my use of an unordered list here, just to drive the point home)
Selectors level 4 seeks to rectify this limitation by allowing :nth-child(An+B of S)2 to accept an arbitrary selector argument S, again due to how selectors operate independently of one another in a compound selector as dictated by the existing selector syntax. So in your case, it would look like this:
table.myClass tr:nth-child(odd of .row)
Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road.
In the meantime, you'll have to use a script to filter elements and apply styles or extra class names accordingly. For example, the following is a common workaround using jQuery (assuming there is only one row group populated with tr elements within the table):
$('table.myClass').each(function() {
// Note that, confusingly, jQuery's filter pseudos are 0-indexed
// while CSS :nth-child() is 1-indexed
$('tr.row:even').addClass('odd');
});
With the corresponding CSS:
table.myClass tr.row.odd {
...
}
If you're using automated testing tools such as Selenium or scraping HTML with tools like BeautifulSoup, many of these tools allow XPath as an alternative:
//table[contains(concat(' ', #class, ' '), ' myClass ')]//tr[contains(concat(' ', #class, ' '), ' row ')][position() mod 2)=1]
Other solutions using different technologies are left as an exercise to the reader; this is just a brief, contrived example for illustration.
1 If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.
2 This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.
Not really..
quote from the docs
The :nth-child pseudo-class matches an
element that has an+b-1 siblings
before it in the document tree, for a
given positive or zero value for n,
and has a parent element.
It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.
nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.
For example
<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
Suppose in above html we want to hide all the elements having rest class.
In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be
.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
display:none;
}
OR
.rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
display:none;
}
Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference
Suppose the html is
<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this
.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
display:none;
}
but if you use nth-of-type css can be this
.rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
display:none;
}
As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.
You may be able to do that with xpath. something like //tr[contains(#class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.
Here is your answer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TEST</title>
<style>
.block {
background: #fc0;
margin-bottom: 10px;
padding: 10px;
}
/* .large > .large-item:nth-of-type(n+5) {
background: #f00;
} */
.large-item ~ .large-item ~ .large-item ~ .large-item ~ .large-item {
background: #f00;
}
</style>
</head>
<body>
<h1>Should be the 6th Hello Block that start red</h1>
<div class="small large">
<div class="block small-item">Hello block 1</div>
<div class="block small-item large-item">Hello block 2</div>
<div class="block small-item large-item">Hello block 3</div>
<div class="block small-item large-item">Hello block 4</div>
<div class="block small-item large-item">Hello block 5</div>
<div class="block small-item large-item">Hello block 6</div>
<div class="block small-item large-item">Hello block 7</div>
<div class="block small-item large-item">Hello block 8</div>
</div>
</body>
</html>
All of the questions around using nth-child and skipping hidden tags appear to be redirecting as dupes of this one so I will leave this here. I came across this blog https://blog.blackbam.at/2015/04/09/css-nth-child-selector-ignore-hidden-element/ that uses a clever css approach to make nth-child ignore hidden elements, as follows:
The following CSS adds a margin right to every second visible element no matter which element has the cpw class.
.cpw {
display:none;
}
.video_prewrap {
margin-right:20px;
}
.video_prewrap:nth-child(2n) {
margin-right:0;
}
.cpw ~ .video_prewrap:nth-child(2n) {
margin-right:20px;
}
.cpw ~ .video_prewrap:nth-child(2n-1) {
margin-right:0;
}
Hope that helps someone who is following the dupe trail for the ignore hidden elements questions!
IF you have same parent class for all selector, Then you use that class document.querySelector("main .box-value:nth-child(3) select.priorityOption");
Because in that case document.querySelector("main .box-value select.priorityOption:nth-child(3)"); Not working. Thank You
<div class="card table">
<div class="box">
<div class="box-value">
<select class="priorityOption">
<option value="">--</option>
<option value="">LOREM</option>
<option value="">LOREM</option>
</select>
</div>
<div class="box-value">
<select class="priorityOption">
<option value="">--</option>
<option value="">LOREM</option>
<option value="">LOREM</option>
</select>
</div>
<div class="box-value">
<select class="priorityOption">
<option value="">--</option>
<option value="">LOREM</option>
<option value="">LOREM</option>
</select>
</div>
</div>
</div>
Not an answer to "Can someone explain why?" since other answers has explained.
But as one possible solution to your situation, you may use custom tags for the rows and cells, say <tr-row>, <td-row>, then :nth-of-type() should work. Don't forget to set style display: table-row; and display: table-cell; respectively to make them still work like table cells.
Inside an each loop, I need to add a class if the current element contains an img not anything else. Here's my latest iteration of not working code, which --- though not right --- probably gives you the idea anyway.
$(".details").each(function(index){
$(this).has("img").not(:contains("p, ul, ol, div, span")).addClass('screenshot-only');
});
Obviously I'm trying to exclude this if it also contains any of p, ul, ol, div, span -- so helping me fix that would be great.
If there's a way to select if this has only img and nothing else at all, that would be better.
:contains("p, ul, ol, div, span") should go into quotes since the Sizzle Engine will parse it as String:
':contains(p, ul, ol, div, span)'
but that's most likely not your main issue here, :contains if you read the jQuery docs searches for TEXT, not DOM nodes
rather take a look at https://api.jquery.com/has-selector/ or https://api.jquery.com/has/
A quick way would be using it in combination with https://api.jquery.com/only-child-selector/
$(".details:has(img:only-child)").addClass("screenshot-only");
Example
$(".details:has(img:only-child)").addClass("screenshot-only");
.screenshot-only {background: gold;}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="details">
<img src="//placehold.it/40x40/0bf">
</div>
<div class="details">
<img src="//placehold.it/40x40/0bf">
<p>foo</p>
</div>
<div class="details">
<img src="//placehold.it/40x40/0bf">
</div>
or if you rather want to target such images instead:
$(".details:has(img:only-child)").find("img").addClass("screenshot-only");
.screenshot-only {border: 5px solid gold;}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="details">
<img src="//placehold.it/40x40/0bf">
</div>
<div class="details">
<img src="//placehold.it/40x40/0bf">
<p>foo</p>
</div>
<div class="details">
<img src="//placehold.it/40x40/0bf">
</div>
You can do the following:
$(".details").each(function(index){
$(this).has("img:first-child:last-child").addClass('screenshot-only');
});
Working JSFiddle
Edit: As pointed out in other posts, you can also use :only-child selector instead of :first-child:last-child. Moreover, you can simply get rid of the each if you just want to add a class to each matching element as Roko C. Buljan's answer shows.
If you aren't attached to jQuery with plain javascript which that is all jQuery is you can do a test for it via:
`if (this.contains("img")) {
return; // doesn't do anything
} else {
$(this).addClass('screenshot-only');
}
` is much easier and is 5 lines using the DOM.
// then just
Ok so I have several blocks of code that look like:
<div class="news-sec">
<h3 class="col-xs-8">heading</h3>
<p class="col-xs-4>paragraph</p>
</div>
<div class="news-sec">
<h3 class="col-xs-8">heading</h3>
<p class="col-xs-4>paragraph</p>
</div>
<div class="news-sec">
<h3 class="col-xs-8">heading</h3>
<p class="col-xs-4>paragraph</p>
</div>
My trouble is that the class is being output by drupal. I need the first one not to have the bootstrap classes, however because they are all the same field they all get spit out wrapped up in the col-xs-# divs. I figure I can write some css to negate the effects of bootstrap such as:
.news-sec h3:first-of-type{
width:100%;
float:none;
}
What I've learned though is that this will affect every .news-sec top level h3 instead of looking at only the first .news-sec.
Is there a way to accomplish what I want to do without js.
PS My drupal dev is out for the week and I can't edit the way it's being output, only after.
.news-sec:first-child h3 is what you want. This gets the first .news-sec and applies the style to its h3. Note how I've applied the pseudo selector (:first-child) to the .news-sec instead of the h3
(Compare this to your code: .news-sec h3:first-of-type -- Your code was looking for the first h3 inside of all .news-sec)
Here's a demo:
.news-sec:first-child h3 {
color: red
}
<div class="news-sec">
<h3 class="col-xs-8">heading</h3>
<p class="col-xs-4">paragraph</p>
</div>
<div class=" news-sec ">
<h3 class="col-xs-8">heading</h3>
<p class="col-xs-4">paragraph</p>
</div>
<div class="news-sec">
<h3 class="col-xs-8">heading</h3>
<p class="col-xs-4">paragraph</p>
</div>
Side note: You're missing some quotes in your provided HTML code near each col-xs-4.
.news-sec h3:first-child targets the first and only the first.
Expectation: Simple 4 line menu, on hover - all divs except the one hovered over with class .snav should lower css font-size to 5px
**** OK PEOPLE - Yeah i know there is a CSS ONLY solution and I know other approaches for resolution -- let me clarify, I was just playing with Jquery selectors and methods, and the Jquery selector I commented out was EXPECTED to work as i listed above, it didn't so i changed it. my question was seeking an explanation for why that commented out selector FAILED ****
In looking at the structure and Jquery below, I expected both Jquery selector versions of the .mouseover to perform the same way, however the one commented out does not perform as expected. instead: It applies the font-size change to all .snav classes and does not exclude the (this) object as expected. I'm looking for someone to explain to me why one selector works but the other does not perform the same way.
//$('.snav').mouseover(function() {
// $('.snav:not(this)').css("font-size","5px");
//});
$('.snav').mouseover(function() {
$('.snav').not($(this)).css("font-size","5px");
});
$('.snav').mouseout(function(){
$('.snav').css("font-size","15px");
});
.snav {font-size:15px; height:30px; line-height:30px;cursor:pointer;width:120px; border:thin solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">
<div id="nav1" class="snav">HOME</div>
<div id="nav2" class="snav">PAGE 1</div>
<div id="nav3" class="snav">PAGE 2</div>
<div id="nav4" class="snav">PAGE 3</div>
</div>
Your issue is because you're using this as a string in the :not() selector, whereas you need to use the this keyword instead, to reference the element itself:
$('.snav').mouseover(function() {
$('.snav').not(this).css("font-size", "5px");
});
That said, there's no need for Javascript here, you can achieve this in CSS alone:
.snav {
font-size: 15px;
height: 30px;
line-height: 30px;
cursor: pointer;
width: 120px;
border: thin solid black;
}
#menu:hover .snav {
font-size: 5px;
}
#menu .snav:hover {
font-size: 15px;
}
<div id="menu">
<div id="nav1" class="snav">HOME</div>
<div id="nav2" class="snav">PAGE 1</div>
<div id="nav3" class="snav">PAGE 2</div>
<div id="nav4" class="snav">PAGE 3</div>
</div>
You've got this embedded in the string; it won't (and can't) be evaluated as this as it exists in the function. Try
$('.snav').mouseover(function() {$('.snav').not(this).css("font-size","5px"); });
Inside jQuery/Sizzle or the browser's native querySelectorAll(), that string "this" is just the letters t h i s. That code has no way of knowing the value of this in your function. You simply cannot create a selector string that involves a DOM element reference directly.
You can't use this in a selector string.
The this keyword exists in JavaScript and references the current context where the code is running. There is no this keyword for CSS selectors, it doesn't know about the JavaScript context.