简体   繁体   English

“classList.add”不会将类添加到 div 和表单元素

[英]“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.我目前遇到了无法通过 classList.add 方法向 div/form 元素添加类的问题。 The same very method works perfectly for other elements like input or button.同样的方法非常适用于输入或按钮等其他元素。 However, no magic happens with the div and the form.但是,div 和表单没有任何神奇之处。

Please, ignore that the JS code is linked externally within the HTML.请忽略 JS 代码是在 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.有关使用 classList 及其属性的信息,请参阅MDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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