tom3883
tom3883

Reputation: 1

.innerHTML doesn't print anything out inside div's

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.

Upvotes: 0

Views: 286

Answers (2)

Quentin
Quentin

Reputation: 943571

<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.

Upvotes: 4

Carl Fink
Carl Fink

Reputation: 434

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";

Upvotes: -1

Related Questions