try to loop through objet & array by pressing button and show every object inside the DOM but it's just show the last objet once i press the button
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">press</button>
<h1 id="name">name </h1>
<h1 id="age">age</h1>
<script >
const info =[{name : "john", age :"20"},{name : "bob", age :"25"},{name : "wil", age :"30"}]
const btn = document.getElementById('btn')
const name1 = document.getElementById('name')
const age = document.getElementById('age')
btn.addEventListener('click', show)
function show(){
for( i = 0; i < info.length; i ){
name1.innerHTML = info[i].name
age.innerHTML = info[i].age
}
console.log(info);
}
</script>
</body>
</html>
CodePudding user response:
You can create an index
variable and store the current index and then get the element at that particular index and then increament it at the end. This is how you can get one by one name
and age
till last.
const info = [{
name: "john",
age: "20"
}, {
name: "bob",
age: "25"
}, {
name: "wil",
age: "30"
}]
const btn = document.getElementById('btn')
const name1 = document.getElementById('name')
const age = document.getElementById('age')
btn.addEventListener('click', show)
let index = 0;
function show() {
if (index < info.length) {
name1.textContent = info[index].name;
age.textContent = info[index].age;
index ;
}
}
<button id="btn">press</button>
<h1 id="name">name </h1>
<h1 id="age">age</h1>
CodePudding user response:
Just look at your code here.
for( i = 0; i < info.length; i ){
name1.innerHTML = info[i].name
age.innerHTML = info[i].age
}
When first time loops runs (for index 0), it stores the value (john and 20) in the html h1 tags.
<h1 id="name">name </h1>
<h1 id="age">age</h1>
And now when the loop run for index 1, then (bob and 25) is storing in the same h1 tags. So, previous values vanished. So in this way, the loop keeps running until the last index. So, it is showing only the last values of the array.
There is a solution that you can do. I have modified your code.
for( i = 0; i < info.length; i ){
if (i = 0){
name1.innerHTML = info[i].name
age.innerHTML = info[i].age
}
else{
name1.innerHTML = info[i].name
age.innerHTML = info[i].age
}
}
In this way, all the names and ages will be show in the h1 tags. This is just for basic understanding that where you are doing mistake.
If you want to show each name and age pair on different h1 tags. You can use Nodes. You create h1 element in the Javascript, and then put text inside the h1 and then use appendChild to place it as a last child in any div you wanted to place or you can use insertBefore to place it as the first child.
You can see the Link of W3Schools mentioned below to understand how element nodes are created and append in the html.