0

Here i want to select the second LI of UL using DOM and mainuplate it , i know how to select first and last element but i am not able to select second ,third and so on element . How to do it?


I want to change the "second" written on the html page(see picture 2 below) to my name using DOM.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43

5 Answers5

4
let list = document.querySelector("ul").querySelectorAll("li");

for(let i = 1; i < list.length - 2; i++){
     list[i].doSomething();
} 
Yura Shtefanko
  • 139
  • 1
  • 2
  • 6
1

You can use querySelectAll and length proprety like this:

var el = document.querySelectorAll('ul > li');
el[el.length-2].textContent="Shubham Kandpal";

or using jquery's eq() method like this:

$("ul > li").eq(-1).text("Shubham Kandpal");
0

Use nth-child

ul > li:nth-child(2)
Chris Wong
  • 564
  • 4
  • 4
0

Please use this javascript selector to select the Second (LI) option.

document.querySelector('ul li:nth-child(2)')

0

Another possible way, besides querySelector, is by adding a class or an Id and getting it:

Adding using a class

function myFunction() {
  let x = document.getElementsByClassName("className");
  x[1].textContent = "Whatever you want to name it now"; 
  // 1 because it is the second position
}

or by id

function myFunction() {
  let x = document.getElementById("idName");
  x.innerHTML = "Whatever you want to name it now"; 
  // You can also use innerHtml to change the text
}
tcsd
  • 1
  • 1
  • I believe it should be `x.innerHTML` instead of `x[1].innerHTML` when querying by id. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) – Josh Apr 03 '21 at 15:38
  • 1
    Yes! Thank you! and I am sorry. – tcsd Apr 06 '21 at 03:17