Reputation: 1
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"> </h3>
<p id="p1"> </p>
<p id="p2"> </p>
</section>
<section id="s2">
<h3 id="h32"> </h3>
<p id="p3"> </p>
<p id="p4"> </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
Reputation: 943571
<h3 ="h31"> </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"> </h3>
<p id="p1"> </p>
<p id="p2"> </p>
</section>
<section id="s2">
<h3 id="h32"> </h3>
<p id="p3"> </p>
<p id="p4"> </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
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