skip to Main Content

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


  1. 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 the querySelector 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") method

    document.querySelectorAll('a[ myOwnAttribute="hello" ]').forEach(a=>{
      a.setAttribute('class','class-hello'); //or a.classList.add('class-hello');
    });
    
    
    document.querySelector('a[ myOwnAttribute="goodbye" ]').setAttribute('class','class-goodbye');
    .class-hello{
      color:red
    }
    .class-goodbye{
      color:green
    }
    <ul>
      <li><a href="#" myOwnAttribute="hello">Click me 1</a></li>
      <li><a href="#" myOwnAttribute="hello">Click me 2</a></li>
      <li><a href="#" myOwnAttribute="hello">Click me 3</a></li>
    </ul>
    
    <a href="#" myOwnAttribute="goodbye">Or Click me</a>
    Login or Signup to reply.
  2. Please check your original snippet: you don’t have a # in value of myOwnAttribute. In your querySelectorAll 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 use setAttribute, 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

    let tag = document.body.querySelector('a[myOwnAttribute="hello"]');
    tags.setAttribute('class', 'class-hello');
    <html>
    
    <body>
      <a href="#" myOwnAttribute="hello">Click me</a>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search