简体   繁体   中英

“classList.add” doesn't add a class to a div and a form elements

I currently stumbled upon trouble with the inability to add a class to div/form elements via classList.add method. The same very method works perfectly for other elements like input or button. However, no magic happens with the div and the form.

Please, ignore that the JS code is linked externally within the HTML. Here all that matters that these two lines don't work:

form.classList.add = "formList";
buttonWrapper.classList.add = "buttonContainer";

 (function(){ function formCreation () { //Here I add elements" let container = document.createElement('div'); let form = document.createElement('form'); let input = document.createElement('input'); let buttonWrapper= document.createElement('div'); let buttonCreator = document.createElement('button'); let buttonRemover = document.createElement('button'); input.placeholder = 'Enter your new task'; buttonRemover.textContent = 'Delete' buttonCreator.textContent = 'Add'; //Here I'm trying to add classess// form.classList.add = "form"; //It won't work for the form' buttonWrapper.classList.add = "buttonContainer"; //Neither it would work for the buttonWraper div" input.classList.add('input'); buttonCreator.classList.add('creator'); buttonRemover.classList.add('remover') container.append(form); buttonWrapper.append(buttonCreator); buttonWrapper.append(buttonRemover); form.append(input); form.append(buttonWrapper); return { form, input, buttonCreator, }; } document.addEventListener('DOMContentLoaded', function () { let containerApp = document.getElementById('container'); let heading = createAppTitle('Things to be done'); let todoItem = formCreation(); let listItself = todoListCreator(); containerApp.append(heading); containerApp.append(todoItem.form); containerApp.append(listItself); }); }());
 <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div id="container" class="container"></div> <script src="index.js"></script> </body> </html>

I don't understand how this code would work on any element type.

The format:

form.classList.add = "formList";
buttonWrapper.classList.add = "buttonContainer";

is wrong.

Try

form.classList.add("formList");
buttonWrapper.classList.add("buttonContainer");

See MDN for info on using classList and its properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM