Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css Selector - Select all siblings until a certain sibling

We wish to avoid an excessive class usage on our code.

We have the following html structure:

<div id='hello'></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div id='hello2'></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div id='hello3'></div>
<div></div>
<div></div>

How can we select, for example, all divs after #hello, but just until #hello2?

Is this possible using a mere css selector?

Can we achieve this using a script language (jquery) ?

Update:

Despite needing a selector, that indeed work, I need this to be placed inside a javascript conditional... Sorry for not mention it up front and more clearly.

like image 217
MEM Avatar asked Dec 09 '22 03:12

MEM


2 Answers

You don't need JS (nor jQuery framework), it's CSS task.

Use siblings selectors:

<style>
    #hello ~ div {background: red} /* four divs after #hello will be red */
    #hello2, #hello2 ~ div {background: white} /* reset red background to default, #hello2 and all next will be white */
</style>

https://jsfiddle.net/sgdedg9z/

like image 121
pavel Avatar answered Feb 04 '23 18:02

pavel


you can use jquery

$( "#hello" ).nextUntil( hello2, "div" )

https://api.jquery.com/nextUntil/

like image 32
Vineeta Mehta Avatar answered Feb 04 '23 16:02

Vineeta Mehta