0

I get null when I try to do getelementbyid on dynamic loaded in div I tried window.onload = function () { and $(window).load(function() {

index.html:

<main >

    <div id="main-div">

    </div>

</main>

homepage.html:

<!-- categories Slider -->
<div class="container-fluid">
    <div class="site-slider-two px-md-4">
        <div class="row slider-two text-center" id="homepageCategories">

javascript:

function loadHomePage() {

    $("#main-div").load("homepage.html", function () {
}
}

function showCategoriesHomepage(categories) {

    window.onload = function () {

        homepageCategoriesId = document.getElementById(homepageCategories);

        homepageCategoriesId.innerHTML = "";

        //For loop that loops true all the categories
        for (var i = 0; i < messages.length; i++) {

            //Create dynamic li elements with child p elements
            var mainDiv = document.createElement('div');
            var span = document.createElement('span');
            var img = document.createElement('img');


            span.setAttribute("class", "border site-btn btn-span");

            img.setAttribute("src", categories.image);

            //Fills the p elements with user_id, description, created_at
            span.appendChild(document.createTextNode(categories.name));
            mainDiv.appendChild(img);
            mainDiv.appendChild(span);
}
}

After the homepage is loaded I make a call to the api and after that is finished I try to getelementbyid on the div but it returns null

1
  • When/where are you calling showCategoriesHomepage function? Did you read the jQuery load() documentation? The method provides a callback, why not use it? Why do you use window.onload from within your function? You need to provide a minimal reproducible example that allows to reproduce the problem and describe clearly what you want to achieve. Commented Feb 22, 2020 at 18:25

1 Answer 1

0

Change this line...

homepageCategoriesId = document.getElementById(homepageCategories);

...to this

homepageCategoriesId = document.getElementById('homepageCategories');
Sign up to request clarification or add additional context in comments.

2 Comments

thats when you know you have programmed for to long XD
@ThomasPonzo I know that sir haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.