Display name
Display name

Reputation: 53

How do I add multiple classes to an element with JS?

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?

Upvotes: 3

Views: 4348

Answers (2)

Lewis
Lewis

Reputation: 4595

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>

Upvotes: 8

imvain2
imvain2

Reputation: 15847

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="comment-field" id="author"></div>
<div class="comment-field" id="email"></div>
<div class="comment-field" id="url"></div>

function CommentStyle() {
        var comment_fields = document.querySelectorAll(".comment-field");
        comment_fields.forEach(function(el){
          el.classList.add("form-control","ulockd-form-bps","required","email");
        });
    }

Upvotes: 2

Related Questions