2

I have many css class how to work that all

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<div class="B3">sgddsg</div>
<div class="B5">dsgdsg</div>
<script>
var nam = document.querySelector('.B3,.B5');
nam.style.width = '100px';
nam.style.height = '100px';
nam.style.backgroundColor = 'blue';
nam.style.color = 'white';

</script>
</body>
</html>

here class B3 is working but B5 not why any solution in one line code.

Abhinash Majhi
  • 499
  • 1
  • 4
  • 16
  • "I have many css class" — Those are HTML classes not CSS classes. CSS doesn't have classes, only class selectors. – Quentin Nov 11 '16 at 10:51
  • Can you post one of your css? because as Quentin said, css doesn't have classess – SUTHANSEE Nov 11 '16 at 10:54
  • @Alpha_Wing — The CSS (other than the manipulations in the JS which we can see in the question) is irrelevant to the problem. – Quentin Nov 11 '16 at 11:04
  • actually i deteted the the href line from head which i havent included , that have css classes in css file. – Abhinash Majhi Nov 11 '16 at 11:23
  • @avinashmajhi — There is still no such thing as a CSS class. You might mean a class selector. You might mean a rule-set. Classes are an HTML thing. – Quentin Nov 11 '16 at 11:38

2 Answers2

7

querySelector returns the first element that matches the selector. If you want to return all the elements then you need querySelectorAll.

querySelectorAll doesn't return a single element though, so you'll need to deal with that.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
5

querySelector only returns the first matching element.

If you want to match more than one element, you'll need to use querySelectorAll, then iterate over the results:

var nam = document.querySelectorAll('.B3,.B5');

for (var i = 0; i < nam.length; i++) {
  var elem = nam[i];
  elem.style.width = '100px';
  elem.style.height = '100px';
  elem.style.backgroundColor = 'blue';
  elem.style.color = 'white';
};
<div class="B3">sgddsg</div>
<div class="B5">dsgdsg</div>
James Donnelly
  • 126,410
  • 34
  • 208
  • 218