我正在使用以下命令来获取元素ID'treeview_sub'的子LI节点,但是它递归地返回了我所有LI的计数。
var treeLILength = document.getElementById("treeview_sub").getElementsByTagName("li").length;
console.log(treeLILength);
<ul id="treeview_sub">
<li id="Invoice" data-expanded="true">Value1
<ul id="Invoice_ul" value="value" data-expanded="true">
<li id="node1">Invoice</li>
</ul>
</li>
<li id="cost" data-expanded="true">Value2
<ul id="cost_ul" value="Cost" data-expanded="true">
<li id="node2">Amount</li>
</ul>
</li>
</ul>
如何只获得长度而不进行递归遍历?
答案 0 :(得分:1)
您可以将var students = [{
name: 'Chris',
track: 'IOS',
achievements: '100',
points: '1000'
},
{
name: 'John',
track: 'Web Design',
achievements: '90',
points: '1000'
},
{
name: 'Brent',
track: 'Front-End',
achievements: '70',
points: '1000'
},
{
name: 'Josh',
track: 'Full-Stack',
achievements: 80,
points: '1000'
},
{
name: 'Nick',
track: 'AI',
achievements: '60',
points: '1000'
}
];
function findStudent() {
let search = prompt("Type name of student. Type 'quit' to exit.");
// Exit the function if the user types 'quit'
if (search == 'quit') return
// Find the student
let student = students.find(s => s.name == search)
let message = "";
// If the student was found, write to the document
if (student) {
message += "<h1>" + student.name + "</h1>";
message += "<p>Track: " + student.track + "</p>";
message += "<p>Achievements: " + student.achievements + "</p>";
message += "<p>Points: " + student.points + "</p>";
document.body.innerHTML = message
}
// The student was not found
// Let the user know and call the function again
else {
alert("That student does not exist. Try again");
findStudent()
}
}
findStudent()
与document.querySelectorAll
一起使用,以仅选择作为直接子元素的>
元素:
li