How to create HTML attributes using raw Javascript

What if you must use raw JavaScript to add attributes to HTML elements in the DOM?

Suppose you have an element selected using querySelector():

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

You can attach an attribute to the attribute by following the steps below:

  1. Create attributes
  2. Set its value
  3. Attach attributes to elements

example:

const attribute = document.createAttribute('id')
attribute.value = `remove-${item.name}`
button.setAttributeNode(attribute)

If the element does not exist yet, you must first create it, then create the attribute, then add the attribute to the element, and finally add the element to the DOM:

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)

Download mine for freeJavaScript beginner's manual


More browser tutorials: