最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I add multiple classes to an element with JS? - Stack Overflow

programmeradmin0浏览0评论

I have below JS code:

<script>
    function CommentStyle() {
        var elementAuthor = document.getElementById("author");
        var elementEmail = document.getElementById("email");
        var elementUrl = document.getElementById("url");
        elementAuthor.classList.add("form-control ulockd-form-bps required email");
        elementEmail.classList.add("form-control ulockd-form-bps required email");
        elementUrl.classList.add("form-control ulockd-form-bps required email");
    }
    window.onload = CommentStyle;
    alert("Hello! I am an alert box!!");
</script>
ffee
<style>
    .form-control {
        border: 1px dashed #cccccc;
    }
</style>

Alert works but the class is not added.Also how can I short this code instead of add new line for every id because the class is same?

I have below JS code:

<script>
    function CommentStyle() {
        var elementAuthor = document.getElementById("author");
        var elementEmail = document.getElementById("email");
        var elementUrl = document.getElementById("url");
        elementAuthor.classList.add("form-control ulockd-form-bps required email");
        elementEmail.classList.add("form-control ulockd-form-bps required email");
        elementUrl.classList.add("form-control ulockd-form-bps required email");
    }
    window.onload = CommentStyle;
    alert("Hello! I am an alert box!!");
</script>
ffee
<style>
    .form-control {
        border: 1px dashed #cccccc;
    }
</style>

Alert works but the class is not added.Also how can I short this code instead of add new line for every id because the class is same?

Share Improve this question edited Jul 4, 2020 at 11:54 Lewis 4,5952 gold badges25 silver badges36 bronze badges asked Jun 10, 2020 at 22:03 Display nameDisplay name 532 silver badges7 bronze badges 1
  • You shouldn't shorten the code, you should instead put the class list into a const and use that instead of repeating the string. – Niet the Dark Absol Commented Jun 10, 2020 at 22:06
Add a ment  | 

2 Answers 2

Reset to default 8

classList.add takes multiple parameters, but will not accept strings with a space in it. You can pass in multiple strings, or if you have your classes stored in a variable classes in the form "firstClass secondClass thirdClass", you can use .split(' ') to split by spaces and then use the spread operator ... to pass the array's contents into classList.add as individual arguments.

This is even simpler for this case, since each element shares the same classes:

(Edit: OP actually ran this code on every page, including those without the relevant elements, so a check was added to exit if they did not exist in the DOM.)

function CommentStyle() {
  let elementAuthor = document.getElementById("author"),
      elementEmail = document.getElementById("email"),
      elementUrl = document.getElementById("url");
      
  // check IDs exist
  if (!elementAuthor || !elementEmail || !elementUrl) return;
  let classes = "form-control ulockd-form-bps required email".split(' ');
  
  elementAuthor.classList.add(...classes),
  elementEmail.classList.add(...classes),
  elementUrl.classList.add(...classes);

  // for demo purposes:
  let [authorClasses, emailClasses, urlClasses] = [
    elementAuthor.className,
    elementEmail.className,
    elementUrl.className
  ];

  console.log({
    authorClasses,
    emailClasses,
    urlClasses
  });
}

window.onload = CommentStyle;
<label for="author">Author</label><br>
<input type="text" id="author"><br><br>

<label for="email">Email</label><br>
<input type="text" id="email"><br><br>

<label for="email">Url</label><br>
<input type="text" id="url"><br>

You don't have to access each field separately by ID, just give them all the same class and loop through that class.

<div class="ment-field" id="author"></div>
<div class="ment-field" id="email"></div>
<div class="ment-field" id="url"></div>

function CommentStyle() {
        var ment_fields = document.querySelectorAll(".ment-field");
        ment_fields.forEach(function(el){
          el.classList.add("form-control","ulockd-form-bps","required","email");
        });
    }
发布评论

评论列表(0)

  1. 暂无评论