0
document.querySelector("#myBtn").onclick = function () {
  console.log("Clicked");
  const h1 = document.querySelector("#myH1");
  const underline = document.createElement("u");
  underline.innerText = "Hey bro.";
  h1.innerText = "";
  h1.append(underline);

  const p = document.querySelector(".myP");
  p.forEach((element) => (element.innerText = "Thank You!!!!"));

  const btn = document.querySelector("button");
  btn.remove();
};
p.forEach((element) => (element.innerText = "Thank You!"));

I got: Error TypeError p.forEach is not a function

Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43

4 Answers4

0

querySelector returns just 1 element. Use querySelectorAll to return a list of elements matching the given selector.

Henrikh Kantuni
  • 833
  • 9
  • 13
0

The Document method querySelector() returns the first Element within the document that matches the specified selector.

You could use the getElementsByClassName instead

var p = document.getElementsByClassName('myP"');
for (let i = 0; i < p.length; i++){
  p[i].innerText = "Thank You!!!!";
} 
Ran Turner
  • 8,973
  • 3
  • 23
  • 37
0

First , Check you createated a query or not.Then variable p is not defined inside the function.use query selector all for return all the elements in the query.

Kamalesh
  • 1
  • 1
0

querySelector returns an array that you can iterate with forEach. so you just need to change querySelector to querySelectorAll.

  const p = document.querySelectorAll('.myP')
  p.forEach((element) => (element.innerText = "Thank You!!!!"));
Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43