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
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.
The setattr() function sets the value of the attribute of an object.
Yes!
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()
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With