0

I am a beginner in html and javascript. I am trying to output some text when a button is pressed, from javascript using .innerHTML but it doesn't print anything out. I am linking the div's by id(if it is possible I would like to avoid loops). Here's the code;

<section class="box special features">
<div class="features-row">
<section>
        <h3 ="h31">&nbsp;</h3>  
        <p id="p1">&nbsp;</p>
        <p id="p2">&nbsp;</p>
</section>
<section id="s2">
    <h3 id="h32">&nbsp;</h3>
    <p id="p3">&nbsp;</p>
    <p id="p4">&nbsp;</p>
</section>
</div>
</section>
<button onclick= "myFunction()" id="button" name="button">ok</button>
<script type="text/javascript">
   function myFunction () {
   h31.innerHTML = ("some text 1");
   p1.innerHTML = ("some text 2");
   p2.innerHTML = ("some text 3");
   h32.innerHTML = ("some text 4");
   p3.innerHTML = ("some text 5");
   p4.innerHTML = ("some text 4");
   }
</script>

Thank you.

tom3883
  • 1
  • 2

2 Answers2

4
<h3 ="h31">&nbsp;</h3>  

You missed the attribute name for the id attribute here.

Consequently, h31.innerHTML = ("some text 1"); errors and the function aborts.

<section class="box special features">
<div class="features-row">
<section>
        <h3 id="h31">&nbsp;</h3>  
        <p id="p1">&nbsp;</p>
        <p id="p2">&nbsp;</p>
</section>
<section id="s2">
    <h3 id="h32">&nbsp;</h3>
    <p id="p3">&nbsp;</p>
    <p id="p4">&nbsp;</p>
</section>
</div>
</section>
<button onclick= "myFunction()" id="button" name="button">ok</button>
<script type="text/javascript">
   function myFunction () {
   h31.innerHTML = ("some text 1");
   p1.innerHTML = ("some text 2");
   p2.innerHTML = ("some text 3");
   h32.innerHTML = ("some text 4");
   p3.innerHTML = ("some text 5");
   p4.innerHTML = ("some text 4");
   }
</script>

This would have been picked up if you had used a validator.

Note, it is considered best practise to use getElementById or another DOM method rather than depending on the non-obvious behaviour of browsers inflating any element with an id into a global JS variable.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

h31 and your other identifiers aren't defined. You need to actually get the HTML elements by doing something like:

document.getElementById("h31").innerHTML = "some text 1";

Carl Fink
  • 434
  • 3
  • 14
  • 1
    That isn't true. Using `getElementById` (note case! JavaScript is case sensitive!) is best practise, but that isn't the actual problem here. That change won't fix the problem because there is no element with the id `h31` in the code in the question. – Quentin Mar 21 '16 at 14:43
  • The creation of a global variable matching the ID of an element is new to me, but I just tried it, and indeed it works! Thank you for the information. – Carl Fink Mar 21 '16 at 14:48