How can I modify CSS using conditional statements in JavaScript?

I currently have something that is not working correctly. My goal is to change the background image of a div named 'three' to a specific jpg if its height is 445.

if ( ".three" == height:"445" ) {".three.style.background-image"= 'url(images/2.jpg)'};

Appreciate any help in advance!

Answer №1

If your HTML structure looks something like this:

<div class="three" style="height: 445px;">
    <p>Random content goes here.</p>
</div>

Then you can use the following JavaScript code to change the background image:

var elems = document.getElementsByClassName('three');
for (var i = 0, len = elems.length; i < len; i++){
    if (parseInt(elems[i].style.height, 10) == 445) {
        elems[i].style.backgroundImage = 'url(images/2.png)';
    }
}

You can see a demonstration of this on JS Fiddle here, where we used background-color instead of background-image.

If your styling is done through CSS, then you need to utilize window.getComputedStyle() like so:

var elems = document.getElementsByClassName('three');
for (var i = 0, len = elems.length; i < len; i++){
    console.log(parseInt(window.getComputedStyle(elems[i], null).height, 10));
    if (parseInt(window.getComputedStyle(elems[i], null).height, 10) == 445) {
        elems[i].style.backgroundColor = 'red';
    }
}

A similar demo using JS Fiddle can be found here.

For an easier approach with jQuery, you could simplify the code as follows:

$('.three').css('background-image', function(){
    return $(this).height() == 445 ? 'images/2.png' : '';
});

Check out this JS Fiddle link for a demo with background-color instead of background=image.

Note that Internet Explorer handles things differently, and there's currentStyle() available as an alternative. For more information on JavaScript, I recommend going through the Mozilla Developer Network's JavaScript documentation.

References:

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

Issue with Fullcalendar: The function properties.push is not supported by Moment

After diligently following the instructions provided by fullcalendar for loading the code using npm packages, I have successfully downloaded three crucial npm packages: fullcalendar 3.10.0 moment 2.24.0 Jquery 3.3.1 Upon initializing the calendar, I enc ...

Dealing with the asynchronous behavior of the NeDB find method: tips and techniques

My Express application utilizes a controller method to invoke the model function verify, which searches a document database file using NeDB's find method. Below is the code for the verify method: verify : function(username, password) { db.find({ ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

Guide on concealing and showcasing an icon within a bootstrap collapsible panel using solely CSS

Hey there, I've been working with Bootstrap's collapsible panel feature and I'm trying to get Font Awesome icons (+ / -) to display based on whether the panel is expanded or collapsed. I'm not too familiar with using CSS for this kind ...

Creating a solo horizontal navigation bar with Bootstrap 4

I am trying to create a horizontal navbar with three nav-pills that are all the same size. However, when I switch to a smaller screen resolution (iPhone 5), the third item always moves to a new line and expands to full width. How can I make sure that the ...

What are the benefits of utilizing custom functions in JavaScript/NPM modules and how can they enhance your code?

As a newcomer to Javascript, I have recently familiarized myself with npm, node.js, and other tools. I am intrigued by two popular packages: mkdirp and glob, which offer basic yet useful functionality. Both mkdirp and glob allow users to provide custom fu ...

Guide to utilizing jQuery for random toggling of classes

My objective is to create a mouseover effect on a box that changes its color randomly. Currently, I have managed to achieve this by toggling one class (e.g. $("#evtTarget").toggleClass(highlighted-2);). However, I am now attempting to select a random class ...

Angular JS Tutorial: How to Nest ng-views

When merging two separate Angular apps into one, I encountered the need to nest ng-views. The structure of my sample code (index.html) looks like this: <!doctype html> <html lang="en" ng-app="myApp"> <head> <meta ch ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...

Quick way to specify type for Observable in Typescript

Exploring Shortcut Declarations When working with TypeScript, I often take a shortcut when declaring object shapes. Instead of creating an interface first and then specifying that the object conforms to that type, I simply do: object: { fizz: boolean, buz ...

What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component: this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe( (data) => { console.log(data.messageHistoryBytes); let file = new Blob( [data.messageHistoryBytes ...

Checking date and time input for accuracy

I have been struggling to set up a validation for my form. I've been researching how to deactivate weekends and holidays in the date time picker. Currently, I am utilizing a JQuery script provided by Trentrichardson found on this link: As someone who ...

Tips for refreshing a webpage after returning from a redirected page

After utilizing certain logic, I am able to redirect to a new page. return RedirectToAction("Index"); If I navigate back to the previous page using the browser's back button, I would like for the "old" page to automatically update with default valu ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Is there a way to dynamically append options to a Bootstrap selectpicker?

I'm attempting to design a dropdown feature that, when activated by clicking on the first list item, displays a new list of related items next to the initial selection. Here's an illustration: https://i.sstatic.net/fMxAj.png My approach involve ...

Leaving a state in Angular after selecting an empty option in the ng-repeat on a select element triggers

When working with angular.js, I am dynamically generating options for a <select> element using the ng-repeat directive. Instead of using ng-options, I opted for ng-repeat because this is for an empty form where I needed to set default values for sel ...

The callback function fails to execute the click event following the .load() method

Hey there, I've hit a roadblock and could really use some help figuring out where I went wrong. Let me break down my script for you. On page1.html, I have a div that gets replaced by another div from page2.html using jQuery's .load() method. Here ...

The enchanting world of CSS background scrolling animations

I am currently developing a website where I have split the hero/header into two sections - one on the left with information and the other on the right with a graphic. I wanted to add a simple parallax effect to the image on the right side, so I used backgr ...

Attempting to transfer a JSON object from a frontend Form Input to an Express backend

Apologies for bringing up what may seem like a basic issue, but I've been searching extensively (even through axios' documentation) and haven't been able to pinpoint exactly what I need to resolve this issue. I have created a simple To-Do we ...

Obtaining AJAX Table Data in Laravel 5.2

When I click the button to display the table, how can I use AJAX in Laravel to update and show all records with new content? The code provided is not working for me. This is my table: <table class="table table-condensed text-right"> ...