user8551674
user8551674

Reputation: 183

addClass breaks JS

I wrote the following code:

document.addEventListener("DOMContentLoaded", ()=>{
    let menu = document.querySelector(' #menu-mainmenu ');
    menu.style.display = 'none';
});

let newButton = document.createElement(' div ');

This code didn't cause any problem.

The moment I've added the following code right under the let newButton, suddenly, as it seems, the JS broke (no JS would load properly anywhere in the site).

newButton.className = 'menuButton';

Console returns this error:

Uncaught DOMException:

Failed to execute 'createElement' on 'Document':

The tag name provided (' div ') is not a valid name.

Why would this happen? What is the problem with creating a div element this way?

Upvotes: 0

Views: 61

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

You have extra spaces around the div tag and that cause an error. Remove them

document.addEventListener("DOMContentLoaded", ()=>{
    //let menu = document.querySelector(' #menu-mainmenu ');
    //menu.style.display = 'none';
    console.log('Worked !!!');
});

let newButton = document.createElement('div');
newButton.className = 'menuButton';

Upvotes: 1

Related Questions