why we cannot use "innerHTML" function directly in loop instead of concatenating the text in order to get a vertical written list?
const pk = document.getElementById('pk');
function validation(){
var word = document.getElementById('name').value;
var arr = word.split(" ");
var i;
for (i = 0; i < arr.length; i++){
console.log(i);
let boko = document.createElement('div');
boko.setAttribute('id', 'boko');
pk.appendChild(boko);
document.getElementById("boko").innerHTML = i;
}
}
here i am not getting output as 0 1 2 3 instead i am getting only 3...
i replaced " text += "The number is " + i + "<br>";"
this statement.. but it seems that its not working please help me solve the issue.
You already have a reference to your div
, so you don't need to assign it an id
-- you can just set its innerHTML
directly.
const pk = document.getElementById('pk');
function validation() {
var word = document.getElementById('name').value;
var arr = word.split(" ");
for (var i = 0; i < arr.length; i++){
let boko = document.createElement('div');
boko.innerHTML = i;
pk.appendChild(boko);
}
}
Check out the documentation for createElement(...)
-- it returns a HTMLElement
which you can modify directly (at least in the case of createElement('div')
)