...">

Transfer the last instance of the class to the parent

I 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 create the last p1 div in each parent div. I tried the code of the last child, but it does not want to accept. Any ideas?

+4
source share
4 answers

This cannot be done with pure css. I recommend this with 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>
Run codeHide result
+4
source

You cannot aim the last element with the class at p1... But if your structure is like this always and right after p1 p2. Then you know that the latter p1will be the penultimate element, you can try the following:

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

Here is some information about : nth-last-child .

DemoFiddle

0

- :

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

:

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

.last-p1 { color: red; }
0

CSS :last-of-type. , , TYPE.

, :

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/

, javascript,

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

jquery... "": -)

0

All Articles