5

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];
2
  • 5
    Give them all the same class name? It would be the point of a classname? Elements can have multiple class names... or just simply use .querySelector() Commented Nov 8, 2016 at 11:29
  • You might want to update the question ; you seem to be asking 'How to access multiple classes', not how to do/create. Commented Nov 8, 2016 at 11:32

2 Answers 2

10

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");
Sign up to request clarification or add additional context in comments.

2 Comments

thanks bro and how to put them in common line like (" .exp (1-2-3-4))"
Welcome :) . If you want to use a single selector for all these classes, you should prefer using attribute selectors (developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors) as mentioned in @Rajesh's answer.
8

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>

1 Comment

At least comment if something is wrong/missing. Revenge votes never help anyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.