0

在这里,我想使用 DOM 选择 UL 的第二个 LI 并对其进行 mainuplate,我知道如何选择第一个和最后一个元素,但我无法选择第二个、第三个等元素。怎么做?


我想使用 DOM 将 html 页面上写的“第二个”(见下图 2)更改为我的名字。

4

5 回答 5

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

for(let i = 1; i < list.length - 2; i++){
     list[i].doSomething();
} 
于 2021-04-01T04:40:24.780 回答
1

您可以像这样使用 querySelectAll 和 length 属性:

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

或者像这样使用 jquery 的 eq() 方法:

$("ul > li").eq(-1).text("Shubham Kandpal");
于 2021-04-01T05:38:45.117 回答
0

使用第 n 个孩子

ul > li:nth-child(2)
于 2021-04-01T04:24:11.943 回答
0

除了 querySelector 之外,另一种可能的方法是添加一个类或一个 Id 并获取它:

使用类添加

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

或通过身份证

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
}
于 2021-04-01T07:01:58.843 回答
0

请使用此 javascript 选择器选择第二个 (LI) 选项。

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

于 2021-04-01T04:46:15.013 回答