如何迭代< ul>使用DOM JS的子元素

发布于 2025-02-03 02:06:26 字数 1035 浏览 3 评论 0原文

因此,我有一个菜单,我希望它可以相应地显示信息,例如:

<ul id="menu-list">
  <li id="about-me"><a href="#">About Me</a></li>
  <li id="skills"><a href="#">Skills</a></li>
  <li id="experience"><a href="#">Experience</a></li>
  <li id="education"><a href="#">Education</a></li>
  <li id="projects"><a href="#">Projects</a></l>
  <li id="contacts"><a href="#">Contacts</a></li>
</ul>

在我的JS文件上,我这样做是为了访问“ li”元素:

let navMenu = document.getElementById("menu-list");
let menuList = navMenu.getElementsByTagName("li");

let skillsButton = document.getElementById("skills");
let skillsEvent = document.getElementById('main-section-skills').hidden = true; 
(text that will display on click is pre-set to hidden = true)

目标是通过“ li”项目迭代以查找其中哪一个具有“ .hidden = false”值并将其更改为“ .hidden = true”,以便当您单击不同的菜单按钮时,每个按钮将只有相关信息,而与其他相关的信息则将bi隐藏。

感谢您的帮助。

So I have a menu, I want it to display information accordingly, for example:

<ul id="menu-list">
  <li id="about-me"><a href="#">About Me</a></li>
  <li id="skills"><a href="#">Skills</a></li>
  <li id="experience"><a href="#">Experience</a></li>
  <li id="education"><a href="#">Education</a></li>
  <li id="projects"><a href="#">Projects</a></l>
  <li id="contacts"><a href="#">Contacts</a></li>
</ul>

and on my JS file I did this in order to access "li" elements:

let navMenu = document.getElementById("menu-list");
let menuList = navMenu.getElementsByTagName("li");

let skillsButton = document.getElementById("skills");
let skillsEvent = document.getElementById('main-section-skills').hidden = true; 
(text that will display on click is pre-set to hidden = true)

The goal is to iterate through "li" items to find which one of those has ".hidden = false" value and change it to ".hidden = true" so that when you click on different menu buttons, each button will so only relevant info and others that are not relevant will bi hidden.

Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

愚人国度 2025-02-10 02:06:26

您可以使用元素获得一系列的孩子。Children

https:/ /developer.mozilla.org/en-us/docs/web/api/element/Children

for (let child of navMenu.children) {
   your logic here
}

用于检查课程,您可以使用element.hasclass甚至:

 element.style.display = 'none'
 element.style.display = 'block'

You can get the array of children using element.children

https://developer.mozilla.org/en-US/docs/Web/API/Element/children

for (let child of navMenu.children) {
   your logic here
}

For checking the class you can use element.hasClass or even:

 element.style.display = 'none'
 element.style.display = 'block'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文