Search code examples
javascriptappendchilddom-manipulationdynamic-html

I am trying to insert a chunk of html code dynamically with Javascript reading smaple json, but unable to do so


Went through a few questions on stackoverflow but could not solve the error. The intention is to modify and add html to the main document reading a JSON structure.

Uncaught TypeError: Cannot read property 'appendChild' of undefined

Update 1:-

  1. Typo was corrected, marked in code.
  2. Defer was introduced at script load in head section, this makes sure the entire document is loaded before the script starts execution.

Here I am trying to read a JSON, and then looping across its content to add to my main html document.

var json={  
        "fruit":[  
      {  
         "fruitname":"Apple",
         "location":"data/png/apple.png",
         "quantity":"25",
         "price":"2"
      },
      {  
         "fruitname":"Mango",
         "location":"data/png/mango.png",
         "quantity":"35",
         "price":"3"
      }
   ]
};

//var cards = document.getElementsByClassName("content"); -- corrected typo
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
    var cardelement=document.createElement('div');
    cardelement.className = 'card';
//    alert(cardelement);
    cards.appendChild(cardelement);
    var object = document.createElement('div');
    object.className = 'object';
//    alert(object);
    cardelement.appendChild(object);
    var image = document.createElement('img');
    image.setAttribute("src", fruits[i].location);
    object.appendChild(image);
    var objectback = document.createElement('div');
    objectback.className = 'object-back';
    cardelement.appendChild(objectback);
    var backfruit = document.createElement('div');
    backfruit.className = 'back-fruit';
    backfruit.innerHTML = fruits[i].fruitname;
    objectback.appendChild(backfruit);
    var backprice = document.createElement('div');
    backprice.className = 'back-price';
    backprice.innerHTML = fruits[i].price + "$ per unit";
    objectback.appendChild(backprice);
    var backquantity = document.createElement('div');
    backquantity.className = 'back-quantity';
    backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
    objectback.appendChild(backquantity);
    
}
*
{
    margin: 0 0;
    border: none;
    text-align:center
        
}


#header
{
    background-color: #F44336;
    font-family: 'Bungee Shade', cursive;
    font-size: 30px;
    height: 20%
}

#footer
{
    font-family: 'Roboto', sans-serif;
    position: fixed;
    height: 80%;
    width: 100%
}

#content
{
    width: 75%;
    height: 100%;
    border-right: thick solid #F44336;
    float: left;
    text-align: left;
    overflow: scroll
}

#cart
{
    background-color:#3F51B5;
    width: 25%;
    border-bottom: thick dashed #F44336;
    float: right
}

.card
{
    display:inline-block;
    width: 100px;
    height: 100px;
    margin: 40px;
    padding: 20px;
    box-shadow: -1px 9px 20px 4px  #000000;       
    border: 5px solid #F44336;
    border-radius: 26px 26px 26px 26px;
    transition: all .2s ease-in-out
}

.object .object-back
{
    display:block;
    position:static
}

.object-back
{
    display: none
}

.object img
{
    height: 100px;
    width: 100px
}

.back-fruit
{
    font-size: 20px;
    padding-bottom: 5px;
    margin-bottom: 10px;
    border-bottom: thin solid 
}

.back-price
{
    font-size: 12px;
    padding-bottom: 5px
}

.back-quantity
{
    font-size: 10px;
    padding-bottom: 10px
}

.back-pluscart
{
    font-size: 15px;
    background-color: #F44336;
    width: auto
}

.back-pluscart img
{
    height: 30px;
    width: 30px
}

.card:hover 
{
    box-shadow: -1px 9px 46px 11px #000000
}

.card:hover .object
{
    display: none
}

.card:hover .object-back        
{
    display:inline-block;
    opacity: 1
}
<!DOCTYPE html>
<html>
<head>
    <title> The Shopkeeper </title>
    <link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel = "stylesheet" type = "text/css" href = "style/style.css" />
    <script type="text/javascript" src="logic/core.js" defer></script>
    <meta name="viewport" content="width=device-width">
</head>

<body>
    <div id="base">
        
        <div id="header">
            <h1> Fruitkart </h1>    
        </div>
        
        <div id="footer">       
        
            <div id="content">
                
<!--
                <div class="card">
                    <div class="object">
                        <img src="data/png/apple.png" />
                    </div>
                    <div class="object-back">
                        <div class="back-fruit">Apple</div>
                        <div class="back-price">2$ per unit</div>
                        <div class="back-quantity">In Stock 25 pieces </div>
                        <div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
                    </div>
                </div>
 
-->
            </div>
            
            <div id="cart">
                    django
                is a big boy    
            </div>
            
        </div>
    </div>
</body>
</html>


Solution

  • Two issues:

    • There is no element with class content. On the other hand there is an element with that id. So you probably want to do:

      document.getElementById("content");
      
    • The script runs too soon -- the elements are not loaded yet when it runs. Either put the script just before the closing </body> tag, or put the code inside an event handler, like

      window.addEventListener('DOMContentLoaded', function() {
          // your code
      });