Home Courses How to Display Array Elements on UI - innerHTML & Loop

How to Display Array Elements on UI - innerHTML & Loop

Goal of This Code

  1. Display array elements on the web page
  2. Add new elements at a specific position
  3. Update UI dynamically when button is clicked


Array Basics


let users = ["anil", "sam", "sidhu", "peter"];

  1. This is a JavaScript array
  2. Index starts from 0
  3. anil → 0
  4. sam → 1
  5. sidhu → 2
  6. peter → 3


Taking Input from User


let val = document.getElementById('value').value;
let pos = document.getElementById('position').value;

  1. value → new element to add
  2. position → where to insert element
  3. getElementById() is used to access input fields


Condition Check


if (pos && val) {
users.splice(pos, 0, val)
}

  1. Prevents empty input
  2. Runs only when both fields have values


splice() Method (Very Important)


users.splice(pos, 0, val);

Meaning:

  1. pos → index where element will be added
  2. 0 → number of elements to delete (0 means no deletion)
  3. 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');

  1. Selects the <ul> element from HTML
  2. Used to insert list items


Clearing Old Data


list.innerHTML = "";

  1. Removes previous list items
  2. Prevents duplication


Loop Through Array


for (let user of users)

  1. Iterates through each element of the array
  2. user represents each item


Display Data on UI


list.innerHTML += "<li>" + user + "</li>";

  1. Adds each element as a list item
  2. += keeps adding new items


innerHTML Concept

  1. Used to insert HTML dynamically
  2. Converts string into HTML elements

Difference:

  1. innerText → shows plain text

innerHTML → renders HTML tags


Button Function


<button onclick="displayElement()">Display Items</button>

  1. Calls function on click
  2. Updates UI instantly


Flow of Execution

  1. User enters value and position
  2. Clicks button
  3. Value is inserted using splice()
  4. Old list is cleared
  5. Loop runs through updated array
  6. New list is displayed


Interview Tip

Common question:

How to add HTML dynamically using JavaScript?

Answer:

  1. Use innerHTML
  2. Create HTML elements like <li> dynamically


Pro Tip (Better Approach)


let li = document.createElement("li");
li.textContent = user;
list.appendChild(li);

  1. More optimized and safer than innerHTML


Example Use Cases

  1. Todo list
  2. Dynamic data display
  3. Chat UI
  4. User list


Share this lesson: