Unable to set or create the 'className' attribute for a newly created div

72 Views Asked by At

I am unable to setAttribute() or even createAttribute() to add a className to a newly created div element. It may be worth noting that the div is created inside of a fetch().then() chain using the createElement command. The code looks like this...

document.addEventListener("DOMContentLoaded", () => {
    let row = 0
    fetch(domain + "/boards/new")
        .then(resp => resp.json())
        .then(json => json.spaces)
        .then(spaces => spaces.forEach( (iRow) => {
            let col = 0
            iRow.forEach( (iCol) => {
                if (iCol != null){
                    let checker = document.createElement('div')
                    let color = iCol.team
                    let c_id = iCol.id
                    checker.createAttribute(className)
                    checker.setAttribute(className, `${color}-checker`)
                    checker.createAttribute(id)
                    checker.setAttribute(id, c_id)
                    checker.createAttribute(data-pos)
                    checker.setAttribute(data-pos, `[${row}][${col}]`)
                    document.body.appendChild(checker)
                }
                col = col + 1
            })
            row = row + 1
        }))
})

It gets all the way to the line checker.createAttribute(className) but then errors out, saying 'className is note defined' which is odd, className SHOULD be understood by the compiler as a global HTML attribute, should it not?

1

There are 1 best solutions below

0
On

https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute

The docs mention that the parameters for the createAttribute() method takes in a string parameter, so it would seem that when you get the error that className not defined, it's because it's trying to find the String that is stored in className