How to Create and Add an HTML Attribute with JavaScript

Learn how to create and add an HTML attribute with JavaScript.

Say you have a button on your website that is supposed to execute a function when you click on it. Unfortunately, someone forgot to add an ID or class value to the button, and you don’t have direct access to the HTML markup right now.

Fortunately, you can just create an attribute and attach it to your button element by using JavaScript.

We need to do 3 things:

  • Create an attribute of the type id
  • Give it a value (name)
  • Add the new attribute+value to the button element

HTML markup

First, the HTML button, which sadly has no ID attribute (buhu), yet:

<button>Click me!</button>

JavaScript

Select your button using querySelector():

const button = document.querySelector('button')

Note:

If your website has more than one button, you can always specify the selector by chaining it. For example, if your button in question is inside a div element with a unique id or class attribute, e.g.:

const button = document.querySelector('.service-section button')

Endnote.

Ok, now let’s create an attribute of the type id:

const attribute = document.createAttribute('id')

And give it a value (name):

attribute.value = `js-button-run-function`

Now attach your newly created attribute to your button element:

button.setAttributeNode(attribute)

That’s it!

Now if you print your button variable to your console you can see that your button has been upgraded:

console.log(button)

// output: "<button id='js-button-run-function'>Click me</button>"

Great, now you can use JavaScript to select this button based on its unique ID, and create a function that will run when users click on the button.

For good measure, let’s confirm that it works. Add this code to your JavaScript file:

// Select button via its new id value
const buttonRunFunction = document.querySelector('#js-button-run-function')

// On click show an alert box
buttonRunFunction.addEventListener('click', function() {
	alert('It works!')
})

If you did everything correctly, you should now see an alert box saying “It works!” popping up when you click on the button.

All the code:

const button = document.querySelector('button')
const attribute = document.createAttribute('id')

attribute.value = `js-button-run-function`

// Attach new attribute to the button
button.setAttributeNode(attribute)

// Select button via its id 
const buttonRunFunction = document.querySelector('#js-button-run-function')

// Add click event to the button
buttonRunFunction.addEventListener('click', function() {
	alert('it works!')
})

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on