'querySelectorAll' does not work

Asked

Viewed 354 times

2

I was doing a test that when clicking the button all 'p' should turn red. Someone knows what is wrong?

function test() {
	document.querySelectorAll('p').style.color = 'red';
}
<!DOCTYPE html>
<html>
<head>
	<title>ola</title>
	<meta charset="utf-8">
</head>
<body>
	<h1>teste</h1>
	<br>
	<hr>
	<p>ola</p>
	<p>oi</p>
	<p>qwerty</p>
	<button onclick="test()">testes</button>
	<script src="teste.js"></script>
</body>
</html>

  • 2

    querySelectorAll returns an array(set) of elements. It is necessary to use a cycle or modify a particular one

1 answer

4


As the friend had said up, to function, you will have to do so...

let elemento = document.querySelectorAll('p')

// Pega apenas o primeiro do array
elemento[0].style.color = 'red';

// pega todos

for(let i = 0; i < elemento.length; i++){
    elemento[i].style.color = 'red';
}
<h1>teste</h1>
	<br>
	<hr>
	<p>ola</p>
	<p>oi</p>
	<p>qwerty</p>

  • Could have done the same c/ getElements Byclassname?

  • I just don’t understand what 'Let is'

  • 1

    @nelson450 Yes, it also works for Classname. Let is a new standard of ES5. basically it is a statement of var. you can subistituir by var

  • @nelson450 Let is restricted to the block scope, usually sialized by ː }. While var if I’m not mistaken is global. This probably creates a lot of difference in consumed memory, but I could be wrong about the real reason for this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.