How to Display Array Elements on UI - innerHTML & Loop
Goal of This Code
- Display array elements on the web page
- Add new elements at a specific position
- Update UI dynamically when button is clicked
Array Basics
let users = ["anil", "sam", "sidhu", "peter"];
- This is a JavaScript array
- Index starts from 0
- anil → 0
- sam → 1
- sidhu → 2
- peter → 3
Taking Input from User
let val = document.getElementById('value').value;
let pos = document.getElementById('position').value;
value→ new element to addposition→ where to insert elementgetElementById()is used to access input fields
Condition Check
if (pos && val) {
users.splice(pos, 0, val)
}
- Prevents empty input
- Runs only when both fields have values
splice() Method (Very Important)
users.splice(pos, 0, val);
Meaning:
pos→ index where element will be added0→ number of elements to delete (0 means no deletion)val→ new element to insert
Example:
users = ["anil", "sam", "sidhu"];
users.splice(1, 0, "peter");
Result:
["anil", "peter", "sam", "sidhu"]
Accessing UL Element
let list = document.getElementById('list');
- Selects the
<ul>element from HTML - Used to insert list items
Clearing Old Data
list.innerHTML = "";
- Removes previous list items
- Prevents duplication
Loop Through Array
for (let user of users)
- Iterates through each element of the array
userrepresents each item
Display Data on UI
list.innerHTML += "<li>" + user + "</li>";
- Adds each element as a list item
+=keeps adding new items
innerHTML Concept
- Used to insert HTML dynamically
- Converts string into HTML elements
Difference:
innerText→ shows plain text
innerHTML → renders HTML tags
Button Function
<button onclick="displayElement()">Display Items</button>
- Calls function on click
- Updates UI instantly
Flow of Execution
- User enters value and position
- Clicks button
- Value is inserted using splice()
- Old list is cleared
- Loop runs through updated array
- New list is displayed
Interview Tip
Common question:
How to add HTML dynamically using JavaScript?
Answer:
- Use
innerHTML - Create HTML elements like
<li>dynamically
Pro Tip (Better Approach)
let li = document.createElement("li");
li.textContent = user;
list.appendChild(li);
- More optimized and safer than innerHTML
Example Use Cases
- Todo list
- Dynamic data display
- Chat UI
- User list