Search code examples
javascriptjqueryhtmldynamicgetelementbyid

How to create dynamic content inside dynamic content in javascript


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


Solution

  • Change this line...

    homepageCategoriesId = document.getElementById(homepageCategories);
    

    ...to this

    homepageCategoriesId = document.getElementById('homepageCategories');