Quantcast
Viewing latest article 16
Browse Latest Browse All 37

Answer by Mohamed Mufeed for Updating an element after it has already been dynamically created in the DOM

The issue with your code is you set the id as symbol-price and you are querying for the element with idprice-price.

Note: you can access an object’s property directly; there is no need for looping if you know the property name.

Also if you are executing setInterval inside the main loop the stockId variable will be available automatically.

eg.

$(function() {    companies = [      {          name : 'Apple'        , symbol : 'AAPL'        , price : '577'        , shares : '1'      }    ]    for (var key in companies) {        var obj = companies[key];        var stockId = obj['symbol'] +'-price';        const prodEl = document.createElement('div');        prodEl.innerHTML = (        `<li class="stocks">  <div class='shares-price'><p id="${stockId}">Price: ${obj['price']}</p></div></li>        `        );        document.getElementById('stock-list').appendChild(prodEl);        document.getElementById(stockId).innerHTML = 200;    }   // set interval outside the main loop    setInterval(function() {        for (var key in companies) {            var obj = companies[key];            var stockId = obj['symbol'] +'-price';            document.getElementById(stockId).innerHTML = 200;        }    }, 1000)});

Viewing latest article 16
Browse Latest Browse All 37

Trending Articles