![](/img/trans.png)
[英]How do I manipulate a DOM Element before it is even added to the HTML?
[英]How can I select the element of html file (except first and last) using DOM and manipulate it?
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.