I'm looking to overwrite a div using JS but the issue is that I'm using append
so the script keep writing data at the end of the div, I have no idea how to fix that, I tried window.location.reload(true)
but, obviously, the data is lost. Can someone point me to the right direction, actually I'm lost. My goal is to refresh / erase or update the div content, preferably, whiteout reloading the page. Here's a runnable code so you can see the problem. Thanks for you help.
$("#getnews").on("click", function() { setTimeout(function() { var path = "https://api.iextrading.com/1.0/stock/" var stock = document.getElementById('userstock').value var end = "/news" var url = path + stock + end $.getJSON(url, function(data) { data.forEach(function (article) { $('#data').append( $('<h4>').text(article.headline), $('<div>').text(article.summary), $('<hr>').text(" "), ); }); }); },200); });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <div class="container"> <p>Search for a stock (Eg: msft, aapl or tsla)</p> <p><input type="text" id="userstock"></p> <p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p> <row id="data"></row> </div> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
$("#getnews").on("click", function() { setTimeout(function() { var path = "https://api.iextrading.com/1.0/stock/" var stock = document.getElementById('userstock').value var end = "/news" var url = path + stock + end $.getJSON(url, function(data) { var html = $("<div></div>"); data.forEach(function (article) { html.append($('<h4>').text(article.headline)); html.append($('<div>').text(article.summary)); html.append($('<hr>').text(" ")); }); $('#data').html(html); }); },200); });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <div class="container"> <p>Search for a stock (Eg: msft, aapl or tsla)</p> <p><input type="text" id="userstock"></p> <p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p> <row id="data"></row> </div> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
Can't you just set the HTML of the container:
var html = $("<div></div>");
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
$('#data').html(html);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.