Michael Anthopolous
Michael Anthopolous

Reputation: 231

Target last instance of class in parent

I have said divs:

<div>
    <div class="p1"></div>
    <div class="p2"></div>
    <div class="p1"></div>
    <div class="p2"></div>
</div>
<div>
    <div class="p1"></div>
    <div class="p2"></div>
    <div class="p1"></div>
    <div class="p2"></div>
</div>

I want to style the last p1 div in each parent div. I've tried some last-child code, but it doesn't want to take. Any ideas?

Upvotes: 6

Views: 841

Answers (4)

dognose
dognose

Reputation: 20899

CSS supports the :last-of-type selector. However, that will not select the last occurence of a class, but the last occurence of a TYPE.

So, as a hack, you could define your own types instead of classes and use that selector:

HTML:

<div>
    <p1>1</p1>
    <p1>2</p1>
    <p2>3</p2>
</div>
<div>
    <p1>1</p1>
    <p1>2</p1>
    <p2>3</p2>
    <p1>4</p1>
</div>

CSS:

p1{
    display:block;
}
p2{
    display:block;
}

div p2:last-of-type{
    background-color:red;
}

http://jsfiddle.net/kwa8y85n/2/

for older browser, you would need to teach them about the element(s) using some javascript, like

<!--[if lt IE 9]> 
<script> document.createElement("p1"); document.createElement("p2"); </script>
<![endif]-->

but then you could pretty much use the jquery way... consider this answer as an "option" :-)

Upvotes: 0

Alex Char
Alex Char

Reputation: 33218

This can't be done with pure css. I reccomend this using jquery:

$("div").find(".p1:last").css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="p1">not</div>
  <div class="p2">not</div>
  <div class="p1">this</div>
  <div class="p2">not</div>
</div>
<div>
  <div class="p1">not</div>
  <div class="p2">not</div>
  <div class="p1">this</div>
  <div class="p2">not</div>
</div>

Upvotes: 5

user663031
user663031

Reputation:

This function finds the last child of some element with a given class:

function last_of_class(elt, cls) {
    var children = elt.getElementsByClassName(cls);
    return children[children.length-1];
}

Now, you can use this to apply a class or some styling:

var last_p1 = last_of_class(parent, 'p1');
last_p1.classList.add('last-p1');

.last-p1 { color: red; }

Upvotes: 0

DaniP
DaniP

Reputation: 38252

You can't target the last element with class for p1 ... But if your structure is like that always and right after p1 is p2 . Then you know that the last p1 will be the penultimate element, you can try this:

.p1:nth-last-child(2) {
    background:black;
    color:white;
}

Here some info about :nth-last-child.

And DemoFiddle

Upvotes: 0

Related Questions