Utilizing the classList property with elements that are hidden from view

How can I use JavaScript to toggle between classes? I can't seem to understand why an element that is set to display: none; is unable to receive a class using classList.

In simpler terms, if I define

#div1{
	width: 25%;
	background-color: #000000;
	display: none;
}

#div2{
	width: 50%;
	height: 10px;
	background-color: #cccccc;
}

.fullview{
	width: 99%;
	height: 500px;
	border-radius: 5px;
	border: 1px solid #000000;
}

and use the following HTML:

<div id="div1">
content here
</div>

<div onclick="myFunction()" id="div2">
content here
</div>

<script>

function myFunction() {
	document.getElementById("div1").classList.toggle("fullview");
}
</script>

the div1 does not receive the fullview class.

However, if I remove display: none; from div1 and apply it to the fullview class instead, the script works fine. But I do not want div1 to be visible or to reserve space until div2 is clicked.

Is this because the script runs before the div is "created"?

What are my alternatives in this scenario?

Answer №1

CSS specificity is key here. ID's hold more weight than classes, so simply adding a class to your element may not be specific enough to override existing styles.

To ensure your styles take effect, incorporate the ID into your style declaration. And don't forget to make sure the element is visible to see the changes.

#div1.fullview{
       width: 99%;
       height: 500px;
       border-radius: 5px;
       border: 1px solid #000000;
       display: block;
}

#div1 {
    width: 25%;
    background-color: #000000;
    display: none;
}

#div2 {
    width: 50%;
    height: 10px;
    background-color: #cccccc;
}

#div1.fullview {
    width: 99%;
    height: 500px;
    border-radius: 5px;
    border: 1px solid #000000;
    display: block;
}
<div id="div1">
    content here
</div>

<div onclick="myFunction()" id="div2">
    content here
</div>

<script>
    function myFunction() {
        document.getElementById("div1").classList.toggle("fullview");
    }
</script>

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

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

What role does the "deep" parameter serve when declaring a watcher in VueJS?

I recently discovered a feature in Vue.js called watchers while working on my web app. As I was exploring the API documentation, I came across a flag known as deep. This flag caught my attention because it defaults to false. I'm curious to know what s ...

Exploring the quirky characters in the PHP mail() function

Currently using the php mail function, it's somewhat effective, although not my preferred method. However, it seems I must make do for now. The issue at hand is that special European characters are showing up strangely in the email. I attempted to se ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

JavaScript prototype error: caught TypeError - attempting to call undefined function

I am facing challenges while attempting to create a Factory in AngularJS. I have moved the code from the controller to the factory and made a few adjustments for it to function properly. Here is the error that I am encountering: "El objeto no acepta la p ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

Removing Borders from Dropdown Tabs in Bootstrap Navbar: A Step-by-Step Guide

I am facing an issue while using Bootstrap 4, as I am unable to remove the border that appears when selecting the drop-down tab. Here is a glimpse of the problem You can view the Inspector View here Check out the relevant code snippet ...

Inserting information into an array: Access the final index consistently with TypeScript

I am interested in dynamically creating a table by allocating it, with the variable nbrBoules: boules:Boule :[] boule:Boule; Boule{id,poids} Method(){ for (var _i = 0; _i < this.nbrBoules; _i++) { this.boule.id = _i; alert(_i); this ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

What are the different ways you can utilize the `Buffer` feature within Electron?

When attempting to implement gray-matter in an electron application, I encountered the error message utils.js:36 Uncaught ReferenceError: Buffer is not defined. Is there a method or workaround available to utilize Buffer within electron? ...

A guide to showcasing JSON data on a webpage using JavaScript

I am currently working on a SOAP WSDL invocation application in MobileFirst. The response I receive from the SOAP WSDL is in JSON format and is stored in the result variable. When trying to access the length of the response using result.length, I encounter ...

When trying to view the page source in Next.js, the page contents do not display

I made the decision to switch my project from CRA to nextjs primarily for SEO purposes. With Server Side Rendering, the client receives a complete HTML page as a response. However, when I check the source of my landing page, all I see is <div id="__next ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

Storing images in Firebase using React JS upon form submission

I've been attempting to upload an image to firebase storage using the following code: const firebase = useFirebase(); const handleSubmit = e => { e.preventDefault(); // state.title && dispatch(createItems(state)); ...

Convert a function into another function when the button is clicked

Hey there, I have an array containing years in my controller: public function getNextYear() { $years = $this->getYears(); foreach ($years as $key => $value) { $y[] = $value + 1; } return $y; } I am displaying this on my ind ...

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

Disappear gradually within the click event function

I have a coding dilemma that I can't seem to solve. My code displays a question when clicked and also shows the answer for a set period of time. Everything works perfectly fine without the fadeOut function in the code. However, as soon as I add the fa ...

What is the best way to design a cell that overlaps with another?

I'm trying to figure out how to make a cell that spans the full width of the existing column and sits on top of the nearest cell. This is part of an effort to create a percentage graph. For example: https://i.sstatic.net/XZahG.png I've experim ...