Reputation: 359
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 (E.g: 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>
Upvotes: 0
Views: 1515
Reputation: 1263
$("#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 (E.g: 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>
Upvotes: 3
Reputation: 1263
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);
Upvotes: 0