Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify STYLE attribute of element with known ID using JQuery

Tags:

html

jquery

css

I got 3 buttons-links triggering some javascript code, with indication if certain button is selected, selected button got style attribute set to

"btn brown selected"

while other buttons got this attribute set to

"btn brown"

only one button can be selected at one time, each of buttons got different unique id, my question is how using jquery access certain button to modify it's style attr. What i need its only how to access by id single button and modify its style attribute to get immediate update on the screen

thanks in advance MTH

like image 214
MoreThanChaos Avatar asked Sep 22 '09 01:09

MoreThanChaos


People also ask

Can we change ID of element in jQuery?

To change the id attribute of an HTML element, you can use the jQuery attr() method which allows you to set an element's attribute value. You can change any HTML element id attribute value by using the example above as a reference.

Which function in jQuery can be used to change the style of an element dynamically?

The css() method is used to change style property of the selected element.

Can I use id in jQuery?

id is not a valid jquery function. You need to use the . attr() function to access attributes an element possesses.


2 Answers

Use the CSS function from jQuery to set styles to your items :

$('#buttonId').css({ "background-color": 'brown'}); 
like image 190
MaxiWheat Avatar answered Sep 25 '22 01:09

MaxiWheat


Not sure I completely understand the question but:

$(":button.brown").click(function() {   $(":button.brown.selected").removeClass("selected");   $(this).addClass("selected"); }); 

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown"); 

But when you want to reverse that change, what do you set it to?

like image 34
cletus Avatar answered Sep 25 '22 01:09

cletus