Exploring Code #52: Of-S Syntax for Nth-Child Selectors

Exploring Code #52: Of-S Syntax for Nth-Child Selectors

I had no idea you could pass a complex selector list into nth-child selectors.

:nth-child(<nth> [of <complex-selector-list>]?) {
  /* ... */
}        

Apparently it has been around awhile in Safari - and only earlier this year was it stably released to Chrome.

You have your vanilla nth-child selectors.

// NHL scoreboard on their website

#headerscoreboard-56209633-d4b5-46f8-8f7d-24fb13988b14 > div.sc-jXbUNg.kBWoTx > div > div.sc-tagGq.dQRuIr > div > div > div > ul > li:nth-child(35)

// li:nth-child(35) <--- this being the plain nth-child selector        

You have your nth-last-child() selector - which counts from the end. As shown by the screenshot below after the little stylesheet I injected into this article from my console turned the text red.

(This is a screenshot) ??????????

But that's all fine and dandy until you want to get really really specific on what you are wanting to select with the nth-child selectors.

And that's where the new(ish) 'of S' syntax really shines.

Apparently (it was news to me), you can go like this:

document.querySelector(':nth-child(1 of .game-score').textContent = 0;        

And with that I can make this hockey game I'm watching a tie game again. It will take a bit more imagination to pretend that the Blues aren't completely sucking right now.

It worked!

Yeah this is a silly example, but the ability to do this just offers more flexibility and ability to really pinpoint down how you are using nth-child selectors.

CSS or JS.

Try it out. You won't need it until you really do. And then you'll be grateful it's there.

要查看或添加评论,请登录

Gabriel Thurau的更多文章

社区洞察

其他会员也浏览了