/

How to Create an HTML Attribute Using Vanilla JavaScript

How to Create an HTML Attribute Using Vanilla JavaScript

If you need to add an attribute to an HTML element in the DOM using vanilla JavaScript, there are a few steps you can follow. Let’s say you have already selected an element using querySelector():

1
const button = document.querySelector('#mybutton');

To attach an attribute to this element, you can follow these steps:

  1. Create the attribute: Use the document.createAttribute() method to create the attribute you want to add. For example, to create an id attribute:

    1
    const attribute = document.createAttribute('id');
  2. Set its value: Use the value property to set the value of the attribute. For example, to set the value to remove-item:

    1
    attribute.value = 'remove-item';
  3. Attach the attribute to the element: Use the setAttributeNode() method to attach the attribute to the element. For example, to attach the id attribute to the selected element:

    1
    button.setAttributeNode(attribute);

If the element does not already exist, you will need to create it, create the attribute, attach the attribute to the element, and then add the element to the DOM.

Here’s an example:

1
2
3
4
5
6
const button = document.createElement('button');
const attribute = document.createAttribute('id');
attribute.value = 'some-value';
button.setAttributeNode(attribute);
button.textContent = 'Click me';
document.querySelector('.container').appendChild(button);

By following these steps, you can easily create HTML attributes using vanilla JavaScript.