繁体   English   中英

如何使用 DOM select html 文件的元素(第一个和最后一个除外)并对其进行操作?

[英]How can I select the element of html file (except first and last) using DOM and manipulate it?

在这里,我想 select 使用 DOM 的 UL 的第二个 LI 并对其进行主更新,我知道如何 select 第一个和最后一个元素,但我无法 Z99938282F0407184259941E18F1ZCF 和第二个元素。 怎么做?

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

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

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

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

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

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

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

使用第 n 个孩子

ul > li:nth-child(2)

请将此 javascript 选择器用于 select 第二个 (LI) 选项。

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

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

使用 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
}

或通过身份证

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM