So, I still making a system when you press a button the system will get all items from a json file.
I do the system for write content on screen (write the tags and other things)
the code I used for for write content on "div":
function update()
{
for (var i = 0; i < database.length; i++)
{
var obj = database[i];
document.getElementById('main').innerHTML += "<a href="
+ obj.link
+ " class="
+ "a" + ">"
+ obj.title
+ "</a> <br class=" + "br" + ">";
console.log(i);
};
};
And I create another function to clear the div, but It don't work, I tryied get element inside div using getElement().
I don't know what I do now, if anyone can help me I will be pretty happy =)
thx
OBS: I new at javascript programming, and sorry about my english '-'
You can clear element content in the same way as you set it:
document.getElementById('main').innerHTML = '';
Simply use Element.innerHTML = "SOME NEW HTML CONTENT" to completely update that element's HTML with new content:
const EL_main = document.querySelector('#main');
const EL_load = document.querySelector('#load');
const fetchDatabase = () => Array.from({length: 20}).map(_ => {
const rand = ~~(Math.random() * 1e4);
return {link: `http://${rand}.html`, title: `Page ${rand}`}
});
function update() {
const database = fetchDatabase();
EL_main.innerHTML = database.reduce((acc, item) => acc + `
<a href="${item.href}">${item.title}</a><br>
`, "");
};
update();
EL_load.addEventListener("click", update);
<button id="load">Load new content</button>
<div id="main"></div>