I’m trying to add an image into a div, but for some unknown reason I simply can’t access the div via JavaScript.
function redirectToProductPage1() {
// location.href = '/product';
const pictureDiv = document.getElementById('productPicture');
console.log(pictureDiv);
}
<body>
<div id="signOutContainer">
<div id="helloNameDiv">
<p id="helloName">hello</p>
</div>
<div id="signOutDiv"> <button id="signOutButton">sign out</button> </div>
</div>
<div id="productPicture">
<div id="advertising3"></div>
<div id="picture">
<img id="img1" src="" alt="test">
</div>
<div id="advertising4"></div>
</div>
<div id="priceAndColorsDiv">
<div class="inputsAndPriceDivs" id="price">
<p>price</p>
</div>
<div class="inputsAndPriceDivs"><input type="color" id="chooseColor"></div>
<div class="inputsAndPriceDivs"><input type="number" id="productAmount" placeholder="product Amount"></div>
</div>
<input type="range" id="chooseSize">
<div id="description">description</div>
<div id="addToCartDiv"><button id="addToCartButton">add to cart</button></div>
<script src='script.js'></script>
</body>
As you can see I’m trying to access the pictureDiv
, but when I print it, I get null.
When I try to print the first div signOutContainer
I get the element properly, also every element inside the div prints properly, every single element that comes after that div, will print null, I tried DOMcontentLoad
to no help, any advice?
Tried DOMcontentLoad
maybe it didn’t load yet or something, tried deleting the first div signOutContainer
and I still couldn’t get the other elements in the html.
2
Answers
The correct name of that event is
DOMContentLoaded
, notDOMcontentLoad
.Try the following Javascript:
Also, do not forget to call your
redirectToProductPage1()
function somewhere.It’s possible that the JavaScript code is executing before the HTML elements are fully loaded and as a result, the productPicture div may not yet exist when the code runs. One way to solve this is by wrapping the JavaScript code inside a DOMContentLoaded event listener, like this:
This ensures that the JavaScript code runs only after the HTML content has been fully loaded. Another thing you can try is moving the script tag to the end of the body element, just before the closing tag. This approach can also help ensure that all of the HTML content has been loaded before the script runs.