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

Excess gap detected in dual-column design

Exploring HTML once again, I'm currently working on creating a 2 column layout that doesn't rely on floats in order to maintain the natural document flow. Most solutions I've come across involve floats or tables, which I want to avoid. I als ...

Populate jQuery datatable using an XML response

I received an XML response from my webservice: <TABLE> <ROW> <ID>1</ID> <SEARCHKEY>XYZ</SEARCHKEY> <SUBURB>XYZ</SUBURB> <RATING>NA</RATING> <DELIVERY>sss</DELIVERY> <STATE>XYS& ...

What is the best method to reset numerous select boxes within a form using jQuery?

What is the best way to reset multiple select boxes within a dynamically generated form using jQuery? There are several select boxes that may have selected options The select boxes are not known in advance as they are generated dynamically Some option ta ...

Retrieve the PDF document from the AJAX call and save it as a

My goal is to have the browser automatically download a PDF file that is received from an AJAX response. After reading about how to download a PDF file using jQuery AJAX, I attempted to simulate a click/download event in this way: var req = new XMLHt ...

Discovering the method to extract a Specific Form Field value with JQuery

Recently, I encountered a form that looked like this: <form id="post_comment" action="cmt.php" method="post"> <input type="hidden" name="type" value="sub" /> <textarea id="body"></textarea> </form> To interact with the ...

Surprising sight of a blank canvas behind the font-awesome icon

Is there a way to remove the unexpected white background that appears when adding a font-awesome icon? Here is the HTML code: <div class="notifications-window" id="close-notifications"> <div class="notifications-header&qu ...

What is the best way to align HTML elements in a single row?

I have the following code snippet... <div class="header"> <div class="mainh"> <div class="table"> <ul> <li><a>smth</a></li> ...

PLupload does not support Flash runtime in Internet Explorer 8

I am facing a dilemma with a basic JavaScript function placed within the $(function() { ... }); block. var uploader = new plupload.Uploader({ runtimes: 'html5,flash,silverlight', browse_button: 'pickfiles', c ...

Finding the index and value of a specific HTML element with jQuery click event

I'm currently working on creating an Ajax function to delete items from a list using Jquery ajax. Here is the HTML structure: <ul> <li><a class="del"><span style="display:none;">1</span></a></li> <li& ...

Implement user interface for adding recipients in email application

Below is the script that utilizes jquery $('#AddRecipents').click(function(e){ $('#abcd').append("<input type='text' name='Recipients' size='29'>"); }); The issue is that new textfields are not ...

Modify the text displayed on the upload file button

I'm looking to modify the name of the file upload button in JSON, but I'm unsure of the process Here is the current Json script https://i.stack.imgur.com/pgbcQ.png This is the output of the current Json https://i.stack.imgur.com/NYWkv.png I ...

Submitting information via jQuery

https://i.stack.imgur.com/VU5LT.jpg Currently, I am working on integrating an event planner into my HTML form. However, I am facing difficulty in transferring the data ("meetup", "startEvent", "break") from HTML to my database. Using jQuery, I was able to ...

When using Math.floor(Math.random() * val.length), the result will be a letter rather than a number

Looking to implement a feature where a different background image is displayed randomly upon page visit or refresh. Currently, specifying the images in an array like the example below works well, but I want to be able to pull from a folder. $(document).r ...

Displaying JSON data based on a specific key

My current challenge involves dealing with a JSON string structured like this: {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]} As part of my learning process in Javascript and AJAX, I am attempting to display the different values based ...

Styling a Fixed Header in CSS/HTML - Scroll Effect

Is it possible to hide only the upper part of the nav-bar, similar to the behavior in WhatsApp? I am using material-ui for this particular use-case. Currently, my implementation causes the app-bar to extend only when the scroll position is less than 48px, ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...

Dynamic scrolling text for overflowing text display

Here's a scenario I'm facing: Let's say I have three div tags, each 100 pixels wide: <--- DIV WIDTH ---> Text in div 1 Text in div two, it overflows Text in div three <--- DIV WIDTH ---> Currently, I've set the following C ...

The dropdown feature within a bootstrap button group is malfunctioning

As part of the web track in cs50, I am working on creating a webpage. My goal is to include options for navigating to the next or previous pages, as well as a dropdown menu with all the pages in between. However, when using Bootstrap's code, the dropd ...

The imported font used in Firefox is displaying with a striking underline text-decoration

I am currently using the Cardiff font in a project and attempting to apply the style text-decoration:underline to it. While this works perfectly in Chrome (Version 35.0.1916.114), in Firefox (Version. 29.0.1) the underline appears to be crossing through t ...

Angular's responsiveness is enhanced by CSS Grid technology

I am attempting to integrate a CSS grid template that should function in the following manner: Columns with equal width 1st and 3rd rows - 2 columns 2nd row - 3 columns Order = [{ details:[ { key: '1', label ...