To give an element a class in Javascript (without using jQuery) if it is currently hidden

Apologies if this question is not perfect, as I am still learning. I have been struggling to figure out how to add a class to an ID when the class is hidden using pure JavaScript (without jQuery). Below are my attempts so far:

function hidekeep() {
    document.getElementById("keep-ads").style.display = "none"
}
setTimeout(function () {
    var e = document.getElementById("keep-ads"),
    t = document.getElementsByClassName("adsbygoogle");
    if(t.style.display = "none") {
        e.className += "up";
    }
}, 2e3);
.up {color:red;}
.adsbygoogle {display:none}
<div id="keep-ads">Foo1
</div>
<div class="adsbygoogle">Bar1
</div>

DEMO

Answer №1

When working with JavaScript, remember that = is used as an assignment operator, while == is used for comparison operations.

In order to modify your block of code, follow these instructions:

setTimeout(function () {
    var e = document.getElementById("keep-ads"),
    t = document.getElementsByClassName("adsbygoogle")[0]; // assuming there's only one element with this class name
    if(t.style.display == "none") { // make the necessary change here
        e.className += "up";
    }
}, 2e3);

UPDATE:

If you want to add a class to an id when a class is hidden using JavaScript

Utilize element.style.display = 'none'; to hide an element and check the style.display property of the element.

function hidekeep() {
    document.getElementById("keep-ads").style.display = "none"
}
setTimeout(function () {
    var e = document.getElementById("keep-ads"),
    t = document.getElementsByClassName("adsbygoogle")[0]; // assuming there's just one element with the given class name

    if(t.style.display == 'none') { // modification made here
        e.className += "up";
    }
}, 2e3);

var hideBar1 = function() {
     document.getElementsByClassName("adsbygoogle")[0].style.display = 'none';

};

document.getElementsByClassName("hide-ads")[0].addEventListener('click', hideBar1 , false);
.up {color:red;}
<div id="keep-ads">Foo1
</div>
<div class="adsbygoogle">Bar1
</div>

<button class="hide-ads">
HIDE
</button>

Answer №2

The function document.getElementsByClassName
will return a collection object and not a single element, unlike document.getElementById. Therefore, when you are checking for the style of t.style, it won't be found. Instead, you should try something like this:

document.getElementsByClassName("adsbygoogle").forEach(function(t) {
    if (t.style.display === 'none') e.className += 'up';
});

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

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

Ways to transfer Material-UI FlatButton CSS to a different Button element

I've recently incorporated a loading button object into my website from (https://github.com/mathieudutour/react-progress-button), and now I want to customize it using the Material-UI FlatButton CSS. However, I'm not quite sure how to achieve this ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

"Exciting Changes in Color According to the Active State of vue-route-link

I am trying to find a way to customize the CSS based on whether a link is exact or active. Essentially, when a user clicks on a menu item, I want the underline to change depending on whether the link is an active router-link. Although I was able to accompl ...

Having trouble updating the icon on my website using FontAwsome

Just a heads up - I'm not familiar with HTML/CSS/JS. This template is pre-made, and I'm simply making some adjustments to it. Hello, I'm currently working on my portfolio website and I want to display my projects based on the programming la ...

Modify the value of a variable inside another {{variable}} (not sure what it's called)

I am looking to update the variable "prefs" to reflect either "easy, medium, or hard" options based on user interaction. For instance: THIS {{choice.prefs.title}} NEEDS TO BE UPDATED TO {{choice.easy.price}} or {{choice.medium.price}} or {{choice.hard. ...

Sending a JSON array in an AJAX request results in receiving null values in an MVC application

I've been trying to send an array of JSON objects to my controller action, but it keeps showing up as null. Here's the JavaScript code I'm using: function UpdateSelected() { var items = {}; //Loop through grid / sub grids and crea ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...

The grid fails to apply remote filtering values when an additional Nested ajax call is incorporated alongside the current HttpProxy configuration

Whenever I click for filter/sort for remote filtering, Forms.asp triggers using a proxy and automatically reloads. Previously, when I used the script below to reload the ExtJS grid with Forms.asp returning new XML with filtered grid data, everything worked ...

Is It Possible to Save Data to Local Storage Using Vue.js?

I am currently working on storing data using Vue.js and local storage. By writing localStorage.set('something', 5) in my main.js file, I can view the data in the Chrome dev tools under the 'Storage' section in the 'Application&apo ...

Is there a way to send a non-JSON value to an angular.js http.post function?

Struggling to send two parameters using the HTTP POST method in Angular.js. Here is the code I have implemented: Controller var installerApp = angular.module('installerApp', []); installerApp.controller('InstallerCntlr',function($scop ...

Is there a solution for passing multiseries data in JSON that works with AnyChart in ReactJS since the standard method is not functioning correctly?

I need help implementing a column chart using AnyChart in react with multi-series data. Below is a sample JSON structure that I am having trouble passing to the chart. const multiSeriesSettings = { width: 800, height: 600, type: "column", ...

Efficient State Management with React-Redux for Streamlined HTTP Requests

In the process of developing a React-Redux application, I have encountered a situation where I need to display a cancel button while a specific HTTP request is ongoing. Upon successful execution of the request, the UI should display the results. If the use ...

Numerous jQuery pop-up windows are being generated instead of just one as intended

When I load an editing form asynchronously on my web page using jQuery.get and display it within a jQuery dialog, multiple instances of the div that I apply .dialog to are unexpectedly being appended to document.body. Here is the code snippet for loading: ...

Is there a way to verify user credentials on the server using FeathersJS?

Currently, my single-page app is utilizing feathers client auth and a local strategy for authentication. I have implemented various middleware routes and I am looking to verify if the user is authenticated. If not, I would like to redirect them to /. Bel ...

What is the best way to terminate a "for await ...of" loop if it fails to finish within a specified timeframe?

Is it possible to stop an asynchronous loop if it doesn't finish within a set time frame? I'm working with the following code: (async()=>{ for await(let t of asynDataStreamOrGenerator){ //some data processing } //some other code I n ...