Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the value of a custom attribute

Tags:

jquery

var selector = $(this);

What is the proper code to change the custom attribute data-change-me for selector?

The syntax

selector[data-change-me='someValue'];

Is not working for me

like image 221
user784637 Avatar asked Apr 15 '12 21:04

user784637


People also ask

How do I change my ATTR value?

To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.

Which function is used to change the value of an attribute?

The setattr() function sets the value of the attribute of an object.

Can we modify attribute value of HTML tag dynamically?

Yes!


2 Answers

While Rob Stevenson-Leggett is perfectly correct, it's important to remember that you can use plain JavaScript for this too:

var selector = document.getElementById('div');
selector.setAttribute('data-change-me','red');​

JS Fiddle demo.

References:

  • element.setAttribute().
like image 176
David Thomas Avatar answered Oct 26 '22 11:10

David Thomas


I think you want the attr method.

selector.attr("data-change-me","someValue");

Here's the documentation: http://api.jquery.com/attr/

It's worth pointing out also that it looked like what you were trying to do was treat the jQuery wrapped DOM object as a Javascript object e.g:

Look at the following example for what I mean:

var myObject = {
     "data-change-me":"someValue";
};

myObject["data-change-me"] = "someOtherValue";

This is valid syntax for pure Javascript objects but not jQuery. To learn about Javascript I recommend Javascript the good parts

like image 40
Rob Stevenson-Leggett Avatar answered Oct 26 '22 12:10

Rob Stevenson-Leggett