Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do mutiple css class in one line javascript code

I have css class names - .exp-1 , .exp-2, .exp-3 , exp-4 ... so is there any simple way to write these all in onlike line like ,I m beginner to javascript

document.getElementsByClassName("exp-1")[0];
document.getElementsByClassName("exp-2")[0];
document.getElementsByClassName("exp-3")[0];
document.getElementsByClassName("exp-4")[0];

to

 document.getElementsByClassName("exp-1,exp-2,exp-3, exp-4")[0];
like image 493
Abhinash Majhi Avatar asked Nov 08 '16 11:11

Abhinash Majhi


People also ask

How do I use multiple CSS classes on a single element?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

How do you add multiple classes in JavaScript?

To add multiple classes to an element, select the element and pass multiple classes to the classList. add() method, e.g. box. classList. add('bg-blue', 'text-white') .

Can you give element multiple classes CSS?

Multiple classes can be applied to a single element in HTML and they can be styled using CSS. In this article, we will stick to only two classes. But the concepts used in assigning two classes can be extended to multiple classes as well.

How do I style a different class in CSS?

The . class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.


2 Answers

You can use querySelector and then use css like selectors. It returns the first element of all selected elements. If you want to return all you can use querySelectorAll

 document.querySelector(".exp-1,.exp-2,.exp-3,.exp-4");
like image 65
Mohit Bhardwaj Avatar answered Oct 27 '22 19:10

Mohit Bhardwaj


You can use starts with selector

document.querySelectorAll('[class^=exp-]')

Sample

Array.from(document.querySelectorAll('[class^=t]'), function(el) {
  console.log(el.innerHTML)
})
<div class="t1">1</div>
<div class="t2">2</div>
<div class="t3">3</div>
<div class="t4">4</div>
like image 42
Rajesh Avatar answered Oct 27 '22 19:10

Rajesh