Utilize CSS to style active buttons with JavaScript

In an HTML document, the dynamic generation of divs and buttons using JavaScript can be seen in the code snippet below.

<div style="background: rgb(247, 247, 247);">
  <button class ="xyz" disabled="disabled">Button1</button>
</div>
<div style="background: rgb(247, 247, 247);">
  <button class ="xyz" disabled="disabled">Button2</button>
</div>
<div style="background: rgb(247, 247, 247);">
  <button class ="xyz">Button3</button>
</div>

The challenge is to change the css(background color) of only the last div where the Button is not disabled. Attempts made with jQuery resulted in changing the css for all divs above it. A solution involving either jQuery or JavaScript is sought to specifically target the last relevant div element.

$(".xyz").parent().css({ "background": "rgb(95, 49, 49)" }); 

Answer №1

To achieve the desired outcome, it is recommended to utilize both :not() and :disabled

:not(:disabled)

$(".xyz:not(:disabled)").parent().css({ "background": "rgb(95, 49, 49)" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background: rgb(247, 247, 247);">
  <button class="xyz" disabled="disabled">Button1</button>
</div>
<div style="background: rgb(247, 247, 247);">
  <button class="xyz" disabled="disabled">Button2</button>
</div>
<div style="background: rgb(247, 247, 247);">
  <button class="xyz">Button3</button>
</div>

Answer №2

To achieve the desired result, you can simply apply the last() method before the parent(). Here's an example that demonstrates how it works:

$(".xyz").last().parent().css({ "background": "rgb(95, 49, 49)" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background: rgb(247, 247, 247);">
<button class ="xyz" disabled="disabled">Button1</button>
</div>
<div style="background: rgb(247, 247, 247);">
<button class ="xyz" disabled="disabled">Button2</button>
</div>
<div style="background: rgb(247, 247, 247);">
<button class ="xyz">Button3</button>
</div>
My requirement is to change the css (background color) of only the last div in which the button is not disabled. I'm using jQuery for this task, but currently, it changes the css for all the above divs as well. Can you provide a solution in jQuery or JavaScript for this specific requirement?

Answer №3

Thank you for your query. Applying styles to all div elements when the button is enabled can be achieved using the following code snippet:

The selector to target is button:enabled.

$(function(){
    $("button:enabled").parent().css({ "background": "rgb(95, 49, 49)" }); 
});

Answer №4

If you want to dynamically generate HTML and apply a background color to all enabled buttons, this code snippet will do the trick.

$('button:not(:disabled)').parent().css({ "background": "rgb(95, 49, 49)" });

Check out the JSFiddle for a live example: https://jsfiddle.net/md9pthta/

Answer №5

Here is the live example on Fiddle: https://jsfiddle.net/hvo5fnt1/

Modified JavaScript code:

$(".xyz").last().css({ "background": "rgb(95, 49, 49)" });

Answer №6

Check out this fiddle You can find the jQuery code I added to your script here:

$(".xyz:not(:disabled)").parent().css({ "background": "rgb(95, 49, 49)" });

Answer №7

If you're looking to make changes to a specific element using jQuery, you can utilize the selector feature to target the desired element and then modify its CSS attributes accordingly.

Take a look at the example selector provided below:

$( ".xyz[disabled!='disabled']" ).parent() 

For a live demonstration, check out this Fiddle:

Click here for the Fiddle link

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

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

Switching an :active class using ReactJS

Currently, I am working on creating an onboarding screen where the user is required to select three or more items. Once the user clicks on an item, a purple overlay should remain visible. For reference, this is what I have in mind: Sharing my code snippe ...

"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it& ...

Achieve a Smooth Transition: Utilizing Bootstrap 3 to Create an Alert Box that Fades In upon Click and Fades Out

Incorporating AngularJS and Bootstrap 3 into my web app, there is an "Update" button that saves user changes. Upon clicking the "Update" button, I aim to trigger and display bootstrap's alert box with the message "Information has been saved," followed ...

Obtaining the Div ID After Clicking on a Link

I'm attempting to fade out a box once the X in that box is clicked. I haven't been able to make it work even after searching on Google. I managed to get it working when clicking the div itself using $(this), but my goal is for it to work when the ...

"Occasional issue with Bootstrap Multiselect not persisting selections when page is reloaded via

When I load a page using ajax that contains a form with a bootstrap multiselect, the multiselect stops working after reloading the page in ajax to apply changes. It doesn't expand when clicked (without any JavaScript errors). However, if I submit the ...

Having difficulty positioning content inside a div element

I am working with a set of three divs, each containing a .header class and a .content class. While I have managed to align the .header class correctly, I am facing an issue with aligning the .content class below the header with 10-15px padding on all sides ...

Tips on postponing the loading of an iframe within a collapsed div using jQuery until the div/button is clicked

So I'm dealing with a bunch of these collapsible divs on a single page, each containing an iframe. (I used some CSS to make it look like a button when clicked). The issue is that the page is loading very slowly because it's loading all the domai ...

Guide to retrieving JSON data from a jQuery ajax request

Below is the JSON string generated by json_encode(): [{"ID":"650","DESCR":"FRONTAGE","MAINURL":"images\/98\/30-HEATH (1).JPG","THUMBURL":"images\/98\/30-HEATH (1).JPG","ALBUM":"98"},{"ID":"651","DESCR":"PICTURE","MAINURL":"images\ ...

Animate a box moving continuously from the right to the left using jQuery

I'm trying to create a continuous motion where a box moves right, then left, and repeats the cycle. However, I can only get it to complete one cycle. $(document).ready(function() { function moveBox() { $('#foo').css({ 'ri ...

jQuery Does Not Iterate Through Arrays

I am encountering an issue where I am trying to populate an array with images and then pass them to a variable called $image. However, when I attempt to iterate over this array, the same item is being alerted three times. Here is the problematic code snip ...

Improving the Performance of HTML/CSS Animations - Enhanced Animation Speed

I have created an HTML page with CSS animation and transitions. <div class="container-fluid" id="team"> <div class="row first"> <div class="wrapper"></div> </div> <div class="row second"> <div class="wrapper" ...

How One Simple Click Can Impact Every Button in jQuery Ajax操作

Whenever I try to click a button that should only affect a specific id, it ends up affecting every button on the page by sending data to our API as well. You can check out a snapshot of my page here. Each row has a unique id, but when I click the vote butt ...

a personalized attribute value obtained from executing a function

I am looking to increase a number in the attribute of a div by clicking on a button. The attribute in question is "data-count" and the button is labeled as "insert". The value generated by the function needs to be added to the existing attribute's val ...

Issue with Selenium: Unable to select the WebElement

I am a beginner with selenium and I have encountered a problem while trying to click on a specific element using the following locators. Unfortunately, none of them seem to work as expected and my scripts just skip over that particular line without any err ...

Show information retrieved from fetch api

Hi there! I've been trying to fetch data from the Avascan API and display it on my HTML page, but so far, I haven't had any luck. I've experimented with using the Fetch API, JSON, and AJAX methods, but none of them seem to work for me. Do yo ...

jQuery error: an unexpected token was encountered

I am encountering an issue with an "unexpected token =" error on the line toggleNav = function(evt){ in the code snippet below. Despite going through various similar posts, I am unable to pinpoint why this error is occurring. Any assistance in guiding me ...

Customize DataTables selector by modifying its frame, font, and alignment

I'm experiencing issues with customizing the page selector in DataTables. Although I managed to change the background color to black, the frame around it remains blue. The font color of unselected pages and the "Next" button also do not reflect the c ...

Header and footer remain unaligned

Bookstore.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> ul { list-style-type: none; padding: 20px; overflow: hidden; background-color: black; width:1230px; p ...

Issues with PHP not reflecting changes to MySQL database

I'm struggling to find a solution to the issue I'm facing on various forums. The problem involves two pages, an HTML page and a PHP page. The HTML page simply populates a dropdown list from a database column. Below is a simplified version of the ...