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
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 "=".You can also use a "for" loop instead of manually adding each array item, like so.
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.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.