I am writing a JS, HTML, DOM script ( using Tamper Monkey ) for an ancient website.
The idea is to use bootstrap and format some tables & lists.
These tables, lists etc have no class, id or anything.
So I grab it by tag name and add class name to it.
I could only select 1 tag instance at a time.
Example
document.getElementsByTagName('ul')[0].className = 'list-group';
('ul')[0] gives first instence.
It does not work on just ('ul').
I want to grab every instance of ul at once.
note: I tried document.querySelectorAll('ul').className = '';
Not working. I want to give all ul same class name.
You need to transform the result for querySelectorAll
into an array and apply a forEach
function on it:
const elementsCollection = document.getElementsByTagName('ul')
const elementsArray = Array.from(elementsCollection)
elementsArray.forEach(el => el.className = 'foo')
Or, if you want to use querySelectorAll
:
const elementsArray = document.querySelectorAll('ul')
elementsArray.forEach(el => el.className = 'foo')