Is it possible to use JavaScript to conceal the final custom <div> element on

I have a series of Div elements like this and I want to set an attribute to the last custom div (HRDIV). After that, I need to hide the 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/

Thank you in advance for your assistance!

Answer №1

const divs = document.querySelectorAll(".hrdiv");
 const lastDiv = divs[divs.length - 1];
 lastDiv.setAttribute('customAttribute', 'test');
 lastDiv.style.visibility = 'hidden';

Answer №2

let hrDivs = document.querySelectorAll('#content .hrdiv');
hrDivs[hrDivs.length - 1].classList.add('highlight');
#content .highlight {
    /* display: none; */
    background-color: blue;
}
<div class="main">
  <div id="content">
    <div class="cols">
      <p>First Content</p>
    </div>

    <div class="hrdiv">

      <div class="cols">
        <p>Second Content</p>
      </div>

      <div class="hrdiv">

        <div class="cols">
          <p>Third Content</p>
        </div>

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

      </div>

Answer №3

If you want to find the last occurrence of a div tag with the class name hrdiv, you can repeatedly search for it until there are no more instances of hrdiv left.

Here's an illustration of how this can be achieved:

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

For a practical demonstration, check out this fully functional example: https://jsfiddle.net/ep3cm739/2/

Answer №4

If you have a class named hrdiv for the divs, start by selecting all elements with this classname.

 document.querySelector('hrdiv');

This code will retrieve all elements with the specified class name. Then, target the last element and hide it by setting the attribute to "hidden".

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing JQuery's printThis Plugin in Combination with the Style Attribute

I am currently working on a JavaScript app and I am trying to implement a button that will allow users to print a specific div. To achieve this, I am utilizing a jQuery plugin called printThis (github link) as well as attempting to use window.print(). $(" ...

Numerous hyperlinks cascading out of the lines

I'm struggling to keep two clickable divs side by side in my code. When I apply the link tag, the divs no longer stay in the same row. Can anyone help me fix this issue? See my current code below: <div class="container col-md-12 pt-5"> < ...

Converting images to greyscale or transparency within a ReactJS component

I am exploring ways to transform an image into grayscale or make it transparent before using it as a background in ReactJS. Is there a way to achieve this in ReactJS? My current code snippet is shown below: <GridListTile> <img style={{ -we ...

What is the method to identify which event is activated when interacting with a button on a web browser?

Currently utilizing vue, bootstrap 4, and bootstrap-vue. My main objective is to resolve a visual glitch that emerges when I interact with a button (refer to the animated screenshot provided). This issue is evident at the bottom of the table, where unwant ...

When I use the shift method on one array, it alters the contents of that array

I am encountering a peculiar issue with two arrays of objects in my program. One array is named "Responses" and the other is called "Questions." The problem arises when I remove the first element from an object in the "Questions" array using shift() meth ...

Multiple web pages utilizing Angular app/widget

I have successfully built a chat application similar to Google Hangouts. However, I am facing a challenge with the angular app/widget running on other pages when URL's are changed, causing the app to either remain fixed or restart on the new web page. ...

Node Webkit: No visible content?

Recently, I decided to explore Node-Webkit and encountered an issue. Despite coding the script below, nothing seems to appear on the screen and the file I intended to create remains missing. Even after installing npm for fs and os modules, I still face no ...

Exploring the reach of scope in a directive

Managing a controller responsible for fetching event JSON data, updating the DOM with data if available, and displaying an error message if no data is found: //Controller.js myApp.controller('EventsCtrl', ['$scope','API', fun ...

Angular 2 is all about managing validation messages within controls

I'm currently facing challenges with getting validation messages to display properly in Angular 2. The frequent updates to Angular 2 have made it difficult to find a simple and effective solution online, so please refrain from marking this as a duplic ...

The file is definitely present, yet a 404 error is still showing up

I'm encountering a 404 error for a file that undeniably exists. The file can be found at domain.com/video/videoname.mp4. But when attempting to play it using Flash, the message "video not found or access denied" pops up. This issue persists with rep ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

Is the font-weight feature malfunctioning on Firefox?

I ran into an issue while dynamically generating div elements where certain style properties were not working properly in Firefox. $(".contacttiles").eq(i).append("<div id=mm"+i+"' class=exp style='font-weight:bold;font-size:14px;color:#FFFFF ...

Installation of a cloned Parse server

I downloaded the Parse server repository from parse-server-example and set up MongoDB, as well as installed Node.js packages using npm install. However, when I try to start the app with npm start, I encounter this error in the terminal!! How can I resolve ...

Filling in input field attributes using a custom directive

Here is a JSFiddle link for reference: http://jsfiddle.net/DfLdF/ The issue I am facing involves a controller wrapping a form with certain logic that cannot be defined within the directive hash as a controller. Specifically, I need to dynamically populat ...

Display a div using data from a Model in MVC

I am working with a model List that has fields ContainerId (div id) and Code (HTML code), which I am passing to a Razor View. Can you suggest the most effective way to display the code from the model in the containerId? My initial thought is to utilize j ...

Ensure that the HTML link is valid and authenticated using SESSIONS

When creating a website, one of the initial tasks I like to tackle is adding links at the bottom of the page for checking valid HTML and CSS: HTML5  •   CSS <div> <a href="http://validator.w3.org/check?uri=referer" ...

What is the best way to access JSON data that is saved in a variable located within a separate component?

I'm currently utilizing axios to fetch JSON data from my API, mapping it, and storing it as a variable. I'm struggling to figure out the optimal way to call these variables within my React components. Retrieving and Storing JSON Data as Variable ...

Array of Colors in JavaScript

I recently watched a tutorial on codecademy about randomizing color arrays, but I'm still struggling to get my colors to appear random. It seems like something is not quite right in my code. function getRandomColor() { var color; var colorArr ...

enhancing the style of my Express project with CSS and EJS

Currently, I am facing challenges with linking CSS to my EJS files in a project I am developing using Node/Express/EJS. Despite creating a public folder with a CSS subfolder and the main.css file inside, I am unable to get the CSS to display in the browser ...

How can I fix the error "rootRef.current.contains is not a recognized function" when using the Transition Component in react-transition-group with the latest versions

I am in the process of updating a project from Material-UI 4 to MUI v5, and I have also upgraded react to v18. We utilize the Transition component from react-transition-group within a Modal in one of our components. However, I encountered an error stating ...