Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Choose the last of child in DIV (CSS Selector)

I’d like to select the last of "b" div with "last-child" or "nth-last-child(1)"
However it’s not working properly. The child of div will be updating dynamicaly
so I cannot use nth-of-child(9).

<div class="parent">
    <div class="a">
    <div class="a">
    <div class="a">
    <div class="a">
    <div class="b">
    <div class="b">
    <div class="b">
    <div class="b">
    <div class="b"> <-- this point
    <div class="c">
    <div class="c">
    <div class="c">
</div>

If I select the last of "b" element,
How can I apply my css tags?

.parent > b:last-child{color:#f00;} // It’s not working
.parent > b:nth-last-child(1){color:#f00;} // It’s not working

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Such a selector doesn’t exist. You need to know the exact position with regard to :nth-child or :nth-last-child to select it with CSS only.

You can resort to Javascript, though.

const divs = document.querySelectorAll('.parent>.b');

divs[divs.length-1].classList.add('red');
.parent>div::before { content: attr(class); }

.red { color: #f00; }
<div class="parent">
    <div class="a"></div>
    <div class="a"></div>
    <div class="a"></div>
    <div class="a"></div>
    <div class="b"></div>
    <div class="b"></div>
    <div class="b"></div>
    <div class="b"></div>
    <div class="b"></div> <!-- this point -->
    <div class="c"></div>
    <div class="c"></div>
    <div class="c"></div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading