Ways to dynamically alter the CSS styling of a div element

I'm utilizing a div element with some inline style and a class to override said inline style. My goal is to alter the border of the div upon button click. I attempted the code below, but it did not yield the desired result.

HTML Code:

<div id="test2" class="test" style="height:30px; width:150px; background-color:red; border:1px solid green;"></div>
<button id="test1">Test</button>

Class Style:

div.test{
    border:2px solid black !important;
    background-color:blue !important;
}

Button Code:

$('#test1').click(function(){
    $('#test2').css('border','none !important');
});

Demo: To view a demo, please click HERE.

Please provide any suggestions on adjusting the CSS properties of the element.

Answer №1

Another point to consider is Kartikeya's observation that using !important in the .css method within jQuery won't work as expected due to inline styles being applied. This means that utilizing !important here:

div.text {
    border:2px solid black !important;
}

My recommendation would be to avoid using !important excessively, as it's generally considered a coding practice to steer clear of. If you're adamant about keeping it, an alternative could be employing the .toggleClass method to toggle between having a border or not. However, remember that relying on !important should be a last resort.


Furthermore, bear in mind that modifying the border may impact the box model and how elements occupy space. When removing the border, the element will visually shrink. To prevent this from happening, instead of setting the border to none, try setting it to transparent.

Answer №2

To give your style-change a new look, add an additional class:

div.new_look{
    border:none !important;
    background-color:blue !important;
}

Next, use removeClass() and addClass() to switch the styles:

$('#test1').click(function(){
    $('#test2').removeClass("test").addClass("new_look");
});

Check out the updated fiddle here: http://jsfiddle.net/r28h4vws/6/

Answer №3

To change the background color of an element from a class test to test2, follow these steps:

div.test2 {
    background-color: blue !important;
}

$('#test1').click(function(){
    $("#test2").removeClass("test").addClass("test2");
});

View Example on jsFiddle

Answer №4

Eliminate the !Important from the jQuery code and also from the CSS styling for the border:

HTML

<div id="test2" class="test" style="height:30px; width:150px; background-color:red; border:1px solid green;"></div>
<button id="test1">Test</button>

CSS

div.test{
border:2px solid black;
background-color:blue !important;

}

Javascript

$('#test1').click(function(){
    $('#test2').css('border','none');
});

Check out the updated version: http://jsfiddle.net/r28h4vws/7/

Answer №5

<script>
    var currentStyle = $("#test2").attr("style");
    // Add code below to remove the border CSS
    currentStyle = currentStyle.replace("border:1px solid green;", "");
    $("#test2").attr("style", currentStyle + "border:none !important;");
</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

Utilizing the Web Crypto API to implement encryption and decryption in Typescript

Due to security requirements, data cannot be sent in plain-text to the server and credentials should not be visible in the browser's network tab. Hashing could have been used but existing passwords are already stored with hash and salting applied. To ...

How do I resolve the issue of PHP sendmail form sending empty emails and fix the JavaScript?

I spent the whole day dealing with sendmail.php. Initially, I had an issue with not receiving emails, which I managed to fix. However, after that, I started receiving blank emails. It wasn't a problem with my PHP or HTML code, but rather with the Java ...

An error notification received from the command "jspm install jquery"

As I follow the tutorial on the jspm.io site, everything goes smoothly until I reach step 3. When I try to execute jspm install jquery, an error message pops up. The error reads: warn Error on getOverride for jspm:github, retrying (2). ReferenceError: ui ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

Bringing together two commitments in angularjs

I am facing an issue while trying to combine 2 promises in a service. I have 2 methods - one is "UserService.getAuthenticatedUser()" which fetches the current user information, and the other is "UserService.getAccountTypeData(idUser)" which retrieves the u ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

What are the steps to compile Sencha Touch using sencha-touch.jsb3?

I've been working on modifying the bundled sencha-touch.jsb3 file in an effort to decrease the size of the framework code. Here's what I've done so far: First, I downloaded the Sencha SDK Tools from I then made edits to SenchaTouch/sen ...

Reasons Behind the News Not Being Retrieved Using [XML JS Query]

Can you help me troubleshoot my code? <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>News Site</title> <script> window.document.onload = ...

Use regular expressions and JavaScript to enclose a series of English letters within a wrapper

I am looking to enclose a series or cluster of consecutive English characters within a <span> tag. In simpler terms, I aim to alter the appearance of English language in my writing. Therefore, I need to identify English characters and surround them ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

The significance of font weight is negligible when it comes to printing an HTML webpage

When writing HTML, I include elements like this: <strong>this is basketball</strong> <div>this is basketball</div> <div style="font-weight:700">this is basketball</div> Everything displays correctly in the bro ...

Struggling with integrating a mixin in your Polymer project?

I'm experiencing difficulties trying to implement a mixin in Polymer. I have created --test-theme, but it seems that the style is not being applied inside the element. Any suggestions on where I might be making a mistake? story-card.html <dom-mod ...

Why does the data continue to remain empty?

I am currently working with a JSON object: {"suggestions":["M.I.A.","M.","Mindless Self Indulgence","The Cure","Telefon Tel Aviv","M","J. Ralph","Jason Mraz","Carbon Based Lifeforms","Cycle of Pain","Chantal Kreviazuk","-M-","ayumi hamasaki","R.E.M.","Don ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

Unsubscribing from a socket io connection in Angular can be done

This is how I establish a connection between the client and server using socket io. export class OverviewService { socket:any; readonly uri:string='http://localhost:4000'; constructor(private http: HttpClient) { this.socket = io(t ...

What causes my Excel file to become corrupted when inputting new data?

My intention with this code is to insert "ABC" into cell B3 of an existing Excel document. However, when the file is written, its size decreases significantly and Excel is unable to open it. const excel = require("exceljs"); const template = "./myexcel.xl ...

Is it possible to use a jQuery plugin on a hidden div?

Dealing with some jquery tabs here. I've incorporated a plugin for a scrolling pane of options within the tabs, but it seems to malfunction when clicking on a tab that was hidden on initial page load. Even tried initiating the plugin using the :hidden ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...

I have been working on creating a hangman game, and although I have figured out the logic behind it, I am experiencing an issue where it is not functioning properly. After inspect

I am currently working on a basic hangman game using only HTML and JavaScript. I have the logic in place, but it doesn't seem to be functioning correctly. When I inspected the element, it showed an error saying 'undefined toUppercase.' As a ...

Unable to modify the fill color of SVG elements through iteration

I'm looking to update the fill color of SVG elements by comparing their ids with an array in React. I've successfully looped through all available elements, compared their ids with the data in the array, and generated the correct results. However ...