How to get an element with attribute name and again set a new attribute to the same element, suppose I have an <a href="#" myOwnAttributeName="hello"></a>
.
Now I know how to select this element using document.querySelectorAll('a[myOwnAttribute="#hello"]')
I need to know how will I set an attribute to the selected element. My final tag should look like <a href="#" myOwnAttributeName="hello" class="class-hello"></a>
here I need to add a class name.
Using the setAttribute doesn’t work.
document.querySelectorAll('a[myOwnAttribute="#hello"]').setAttribute('class', 'hello-class')
document.querySelectorAll('a[my-own-attribute="#hello"]').setAttribute('class','hello-class')
<html>
<a href="#" my-own-attribute="hello">Click me</a>
</html>
2
Answers
Using
querySelectorAll
will create a nodelist so you need to iterate through that nodelist in order to modify the properties of one or all elements. Alternatively if there is a single element that you wish to modify properties/attributes for thequerySelector
will allow direct access to selected node.The following snippet shows both approaches – the setting of the new className could more easily be done using
node.classList.add("new_class_name")
methodPlease check your original snippet: you don’t have a
#
in value ofmyOwnAttribute
. In yourquerySelectorAll
you have it. Make sure you query against the proper attribute and value.Please note, if you use
querySelectorAll
, the return value is a NodeList, so if you wish to usesetAttribute
, which works on an Element or Node, you have to select one item (in this case[0]
) and set the new attribute.If you have only one matching item, I suggest to use simple
querySelector