Reputation: 13
I am trying to write some code and I have one issue. Basically I am trying to write some statements (ifs, else etc) and I need to access some <p>
elements from different <div>
sections.
<body>
//works with the one below = changes its value from x to 10
<p id="one" class = "class">x</p>
<script type="text/javascript">
var time = new Date().getHours();
if (time < 20) {
document.getElementById("one").innerHTML = "10";
document.getElementById("two").innerHTML = "10";
}
</script>
<div class="green2">
<p id ="two" class="class" >x</p>
//with this one nothing happens
</div>
I guess it doesn't reach the actual element with id two
so how can I handle it?
Upvotes: 0
Views: 88
Reputation: 121
Your script is being loaded before the two
, you should put your script
tag always at the very bottom of your body
tags (inside them), so that all your content will be loaded first, only then your script.
Upvotes: 3
Reputation: 1032
Alternatively, you can add an event listener such as jQuery's .ready() or javascript's document.onDOMContentLoaded or window.onload events. Then you may place the script where you like and the function will only be executed when the page is ready.
Simply wrap your code in the listener function like such:
<p id="one" class = "class" >x</p>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(){
var time = new Date().getHours();
if (time < 20) {
document.getElementById("one").innerHTML = "10";
document.getElementById("two").innerHTML = "10";
}
});
</script>
<div class="green2">
<p id ="two" class="class" >x</p>
</div>
Upvotes: 0
Reputation: 12209
To expand on Pedro's answer, you can also use jQuery and wrap everything in a document.ready function:
$(document).ready(function(){
var time = new Date().getHours();
if (time < 20) {
document.getElementById("one").innerHTML = "10";
document.getElementById("two").innerHTML = "10";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="one" class = "class" >x</p>
<div class="green2">
<p id ="two" class="class" >x</p>
</div>
This way you can have the JavaScript appear anywhere on the page.
Upvotes: 0