Catch last div of a div

Asked

Viewed 1,676 times

3

Considering this structure:

<div id="PAI">
  <div uniqid="1" class="filho">A</div>
  <div uniqid="2" class="filho">A</div>
  <div uniqid="3" class="filho">A</div>
  <div uniqid="4" class="filho">A</div>
  <div uniqid="5" class="filho">A</div>
</div>

I need to get the number div uniqid = 5 ie always the last of the div with id PAI how to do?

  • last element/object or last "div" ? may happen to exist other elements within a div, e.g., a <span>, an anchor <a>, an Row <hr>

  • @Danielomine the last object will follow the model I demonstrated above always being a div with such attributes but they will always be filled with other elements..

2 answers

7


You can use element.lastElementChild when applied to the parent element gives what you want, the last element.

example: http://jsfiddle.net/7rz7o7u0/

var pai = document.getElementById("PAI");
var ultimoFilho = pai.lastElementChild;
ultimoFilho.style.backgroundColor = 'green';
<div id="PAI">
    <div uniqid="1" class="filho">A</div>
    <div uniqid="2" class="filho">A</div>
    <div uniqid="3" class="filho">A</div>
    <div uniqid="4" class="filho">A</div>
    <div uniqid="5" class="filho">A</div>
</div>

1

Can use document#querySelector().


Getting the last element by class .filho :

var last = document.querySelector(".filho:last-child");
last.style.color = 'red';
<div id="PAI">
  <div uniqid="1" class="filho">A</div>
  <div uniqid="2" class="filho">A</div>
  <div uniqid="3" class="filho">A</div>
  <div uniqid="4" class="filho">A</div>
  <div uniqid="5" class="filho">A</div>
</div>


Getting the last div inside #PAI :

var last = document.querySelector("#PAI div:last-child");
last.style.color = 'red';
<div id="PAI">
  <div uniqid="1" class="filho">A</div>
  <div uniqid="2" class="filho">A</div>
  <div uniqid="3" class="filho">A</div>
  <div uniqid="4" class="filho">A</div>
  <div uniqid="5" class="filho">A</div>
</div>


Getting the element by uniqid=5 :

var last= document.querySelector("[uniqid='5']");
last.style.color = 'red';
<div id="PAI">
  <div uniqid="1" class="filho">A</div>
  <div uniqid="2" class="filho">A</div>
  <div uniqid="3" class="filho">A</div>
  <div uniqid="4" class="filho">A</div>
  <div uniqid="5" class="filho">A</div>
</div>

  • 1

    It should be mentioned that .querySelector works also for us, i.e. can also do document.getElementById('PAI').querySelector(':last-child'); this is useful if you already have a reference to #PAI at hand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.