JQuery, Selecting by attribute value, adding a new attribute

I have an anchor in my HTML. it has a page attribute with a value. So every time I click, I use the page attribute value in js. Now I want to set a style attribute with a background color to show that a specific item is selected. Therefore, I have to select the element by page attribute and add a new attribute with a value for element a.

How do I handle this?

+2
javascript jquery jquery-selectors
Sep 16 '10 at 6:36
source share
3 answers

With HTML like:

<a href='#' page='1'>Link 1</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​<br /> 

You can do:

 $('a[page=1]').addClass('selected').attr('test', 'hi!');​ 

(that is, it is better to change the display using the css class [for example, "selected"] than the style attribute, but calling attr shows how to add the attribute).

+4
Sep 16
source share

To select an item by attribute value, you can use this syntax:

 $('[attribName="value here"]') 

Where attribName should be replaced with an attribute name such as name , title , etc.

To add a new attribute value, you can use the attr method.

Example:

 $('[attribName="value here"]').attr('attribute name', 'attribute value'); 

And you can change the background color:

 $('[attribName="value here"]').css('background-color', 'green'); 

Please note that you must replace the names and values ​​of the attribute attributes to suit your requirements.

+3
Sep 16 '10 at 6:41
source share

Not sure what you are asking .. do you need to find an element with a specific value for the "page" and change its background?

 $("a[page='value']").css('background-color', 'color-code'); 
+1
Sep 16 '10 at 6:40
source share



All Articles