Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why query selector not working for second class

Tags:

html

css

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.

like image 880
Abhinash Majhi Avatar asked Jan 17 '26 15:01

Abhinash Majhi


2 Answers

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.

like image 86
Quentin Avatar answered Jan 20 '26 10:01

Quentin


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>
like image 30
James Donnelly Avatar answered Jan 20 '26 08:01

James Donnelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!