views:

45

answers:

3

Hi,

I have an anchor in my HTML. it has a page attribute with a value. So everytime it is clicked I use the page attribute value in my js. Now I want to set a style attribute with a background color to show that a certain a element is selected. So I have to select the element by page attribute and add a new attribute with a value to the a element.

How do I handle that?

+1  A: 

Not sure what you're asking.. do you need to find the a elemenent with a certain value for "page" and change its background?

$("a[page='value']").css('background-color', 'color-code');
A. M.
thanks that works, but the color I specify in color-code stays when I click on an other a element. It should switch back to default. any idea how to do that?
ArtWorkAD
You use null to unset a css attribute. $("a[page='value']").css('background-color', null).
A. M.
+2  A: 

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

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

Where attribName should be replaced with 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 this is how you can change the background color:

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

Note you should replace dummy attribute names and values as per your requirements.

Sarfraz
A: 

With HTML like:

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

you could do:

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

(i.e. better to change display using a css class [e.g. 'selected'] than the style attribute - but the attr call there shows how to add an attribute).

sje397
but I want to have the selected a element to have selected class, all other elements should not have this class, so how do I remove the class when an other element is selected?
ArtWorkAD
solved that with $(".selected").removeClass('selected');
ArtWorkAD