To do this, first we get the element. We can use the following methods:
We probably want to use anything other than
getElementById since our element doesn’t have an ID yet.
document.querySelector can get an element with any CSS selector and return it.
For instance, given that we have an element with class
foo, we can write:
const el = document.querySelector('.foo');
querySelectorAll, it returns a NodeList with all elements with the given CSS selector.
So we’ve to find the one that’s right for us. But assuming that we want the first element, we can write:
const el = document.querySelectorAll('.foo')
getElementsByTagName, we can get all the elements by their tag name.
For instance, we can write:
const el = document.getElementsByTagName('div')
to get all the divs with the given name.
In all cases, we can get an
HTMLElement object, which has the
id property, which we can use to set the ID of an element by assigning a string to it.
We can write:
el.id = 'bar';
to set the ID of
el above to
id property of an