Bijan Zand
Bijan Zand

Reputation: 417

How can I hide last custom div with javascript

I have some Div like this and i want set attribute to last my custom div (HRDIV) after that i need to set hide to hidden last hrdiv

<div class="main">
  <div id="content">
    <div class="cols">
      <p>Content number 1</p>
    </div>

    <div class="hrdiv">

      <div class="cols">
        <p>Content number 2</p>
      </div>

      <div class="hrdiv">

        <div class="cols">
          <p>Content number 3</p>
        </div>

        <div class="hrdiv">

        </div>

      </div>

http://jsfiddle.net/dxqco8t0/

many thanks to your help my friends ...

Upvotes: 2

Views: 101

Answers (4)

deepak nayak
deepak nayak

Reputation: 1

As you have a class hrdiv for the divs. First select all elements of this classname.

 document.querySelector('hrdiv');

This will return all elements with this class name. Get the last element and set the attribute of hidden.

 document.querySelector('hrdiv').lastElementChild.setAttribute("hidden");

Upvotes: -1

Tdy
Tdy

Reputation: 84

Another way to go about this is to keep looking for the last div tag with hrdiv class as long as there are still hrdiv

Here is a example of how to do that:

var lastHrDiv = document.querySelectorAll('.hrdiv:last-child')[0];
while(lastHrDiv.querySelectorAll('.hrdiv:last-child').length > 0)
lastHrDiv =  lastHrDiv.querySelectorAll('.hrdiv:last-child')[0];

And here is a fully working example: https://jsfiddle.net/ep3cm739/2/

Upvotes: 0

caramba
caramba

Reputation: 22480

var allHrDivs = document.querySelectorAll('#content .hrdiv');
allHrDivs[allHrDivs.length -1].classList.add('xxx');
#content .xxx {
    /* display: none; */
    background-color: red;
}
<div class="main">
  <div id="content">
    <div class="cols">
      <p>Content number 1</p>
    </div>

    <div class="hrdiv">

      <div class="cols">
        <p>Content number 2</p>
      </div>

      <div class="hrdiv">

        <div class="cols">
          <p>Content number 3</p>
        </div>

        <div class="hrdiv">
          LAST HRDIV
        </div>

      </div>

Upvotes: 1

Florian Hecht
Florian Hecht

Reputation: 74

 let elements = document.querySelectorAll(".hrdiv");
 let last = elements[elements.length - 1];
 last.setAttribute('newattribute', 'example');
 last.style.display = 'none';

Upvotes: 2

Related Questions