Tuesday, May 21, 2019

css selectors - Targeting the first class instance on a page with CSS

No such functionality exists in CSS. You will need to use a JS solution to find them on the client machine, or a server-side solution to apply an additional class to the first element with this CSS class. Which to use depends on how important it is to style this item uniquely.


Using jQuery, you could find the first instance of the class via:


var firstAsJQueryObject = $('.showreel').eq(0);
var firstAsDOMElement = $('.showreel')[0];

Using pure JavaScript on modern browsers:


var firstAsDOMElement = document.querySelector('.showReel');

Using pure JavaScript on older browsers:


function findFirstElementWithClass(className){
var hasClass = new RegExp("(?:^|\\s)"+className+"(?:\\s|$)");
for (var all=document.getElementsByTagName('*'),len=all.length,i=0;i if (hasClass.test(all[i].className)) return all[i];
}
}
var firstAsDOMElement = findFirstElementWithClass('showReel');

If you are going to use JavaScript, instead of applying the visual style through JavaScript I would suggest apply a class using JavaScript and still using CSS to style the element:


// Using jQuery for simplicity
$('.showreel').eq(0).addClass('first-showreel');

.first-showreel {
/* apply your presentation here */
}



Edit: Note that the much-higher-voted answer by @mickey_roy is incorrect. It will only work when the element with the class you want is also the first element of its type on the page.


Writing .showreel:nth-of-type(1) means, "Find me the first element with each class name that also has the showreel class applied." If the same element type appears earlier on the page without the class, it will fail. If a different element type shares the same class, it will fail.


The question asks how to select the first instance of the class. See below for an example of how very wrong that answer is for this question.




div { color:red }
.showreel:nth-of-type(1) {
font-weight:bold;
color:green
}

not this

this should be green

not this

not this

not this


not this


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...