skip to Main Content

I am trying to make a site where a user can press a button and then the data from an array can show on the screen. I cannot figure out how to do this. please help!
(p.s. i’m a beginner. please be patient.)

<!DOCTYPE html>
 <html>
  <body>  <!--  ******* BODY OPEN ********** -->

   <button onclick="ShowAllMale()">Do a Function Button</button>
   <p id="btn"></p>

     <!-- ******************** Javascript ********************** -->
     <script> 
     const dogsMale = ["Boris ", "Harley ", "Max"];
     function showAllMale(dogsMale) {
     document.getElementById("btn").innerHTML= dogsMale;
     }
     </script> <!-- *********** Javascript closed ************** -->

   </body> <!--  ******* BODY CLOSED********** -->
 </html>`

2

Answers


  1. An array in JavaScript is considered an "object". You can’t inject an object into the DOM (document object model). You’ll need the other side of the equals sign (innerHTML = …) to be a string.

    You need to get the index of each array item individually. innerHTML removes the content of the desired location, so you’ll have to add to it, hence the "+=" instead of just assigning it with "=".

    function showAllMale(dogsMale) {
      const pBtn = document.getElementById("btn");
    
      // Add each array item
      pBtn.innerHTML += dogsMale[0] + ' '; // Boris
      pBtn.innerHTML += dogsMale[1] + ' '; // Harley
      pBtn.innerHTML += dogsMale[2] + ' '; // Max
    }
    

    You can also use a "for" loop instead of manually adding each array item, like so.

    for (let i = 0; i < dogsMale.length; i++) {
      const pBtn = document.getElementById("btn");
    
      pBtn.innerHTML += dogsMale[i] + ' ';
    }
    

    Check this for reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML


    Make sure that the showAllMale in the button’s "onClick" is spelled the EXACT same as where you declare the function.

    Login or Signup to reply.
  2. functions name needs to match you have ShowAllMale and showAllMale secondly you are not passing anything to the function. you are just using the constant you made. so remove dogsMale from your function.

     
         const dogsMale = ["Boris ", "Harley ", "Max"];
         const ShowAllMale = () => document.getElementById("btn").innerHTML= dogsMale;
         
    <button onclick="ShowAllMale()">Do a Function Button</button>
       <p id="btn"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search