JavaScript JavaScript and the DOM Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

Yogita Verma
Yogita Verma
5,549 Points

My code is not working I can't figure out the problem

index.html
<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <h1 id="myHeading">JavaScript and the DOM</h1>
    <p>Making a web page interactive</p>    
    <p class="li-para">Things that are purple:</p>
    <input type="text" id="myText">
    <ul>
      <li>grapes</li>
      <li>amethyst</li>
      <li>lavender</li>
      <li>plums</li>
    </ul>
    <button type="button" id="bu">Click Me To change para!</button>
    <script src="app.js"></script>
  </body>
</html>
app.js
const head=document.querySelectorAll('h1');
const bu=document.querySelectorAll('#bu');
const inp=document.querySelectorAll('#myText');
const p=document.querySelectorAll('.li-para');
const t=()=>{
p.innerHTML=inp.value;
}
bu.addEventListener('click',t);
Yogita Verma
Yogita Verma
5,549 Points

Its giving me this error on console '' bu.addEventListener is not a function"

2 Answers

Balazs Pukli
Balazs Pukli
46,041 Points

First: you can not use "querySelectorAll()" for ids since the id indicates that there is only one of that element. You can use "querySelectorAll()" for classes and tags, and if there is only one of them, you will have a list of one element. But you can not do that with ids, you have to use the "querySelector()" for ids. (The not plural version.) Examples with both the plural version and the singular version:

const head=document.querySelectorAll('h1');
const bu=document.querySelector('#bu');

Second: you can not access the innerHTML property of a list. Only the elements of the list has innerHTML property, not the list itself. You have to iterate through the list to access it's elements and innerHTML properties thereof. Example:

const t=()=>{
  for (let i = 0; i<p.length; i++)
{
p[i].innerHTML = inp.value;
}
}
bu.addEventListener('click',t);
Yogita Verma
Yogita Verma
5,549 Points

This does not seem to work .I only want the para with class li-para to change when clicking the button accoring to the input value

Balazs Pukli
Balazs Pukli
46,041 Points

I don't know how you expect this program to work. You'll have to figure out which elements do you want to change and access the corresponding css selectors. But in general, what I've commented about the logic of the DOM traversing is correct.

Jimmy Dorvilus
Jimmy Dorvilus
Full Stack JavaScript Techdegree Graduate 27,971 Points

I think you should keep it simple. The following JS code works fine for me.

const p=document.querySelector('.li-para');
const inp= document.querySelector('#mytext');
const bu= document.querySelector('#bu');

bu.addEventListener('click', ()=>{
    p.textContent=inp.value;
});