gpt4 book ai didi

javascript - 如何按类获取可见元素?

转载 作者:行者123 更新时间:2023-12-03 04:44:23 24 4
gpt4 key购买 nike

除了javascript我别无选择。我相信很多人都经历过这个。

HTML 代码

<ul class="recordingslist"></ul>
..
..
..
<div class='test' style="display : none">
<ul class="recordingslist test1" ></ul>
</div>
..
..
..
<div class="testasdasdsad" style="display : none">
<ul class="recordingslist test2"></ul>
</div>

JS代码

recordingslist = document.getElementsByClassName("recordingslist")[0];

我有很多同一类的 ul。现在只有第一个 ul 可见,我想将“test”附加到该可见的 ul 上。我们怎样才能实现这一目标?

提前非常感谢您。

最佳答案

根据您在评论中的说明,您正在搜索第一个 <ul>其父元素 <div> 的元素元素有 display不等于 none 的属性.

鉴于此,我建议:

// here we use Array.from() to convert the supplied Array-like
// NodeList into an Array, in order to use Array methods:
Array.from(

// here we find all <ul> elements with a class of
// 'recordingslist':
document.querySelectorAll('ul.recordingslist')

// we filter the resulting Array of <ul> elements, using
// Array.prototype.filter():
).filter(

// using an Arrow function, in which the 'ul' variable
// is a reference to the current <ul> element of the Array
// of <ul> elements over which we're iterating:
ul => window.getComputedStyle(
// we find the computed CSS properties of the node:
ul.parentNode, null

// and access its 'display' property to ensure that
// it's computed display property-value is not equal
// to the value of 'none' (so it should not be hidden):
).display !== 'none'

// we iterate over those elements retained in the Array,
// using Array.prototype.forEach
).forEach(

// here we use another Arrow function:
// ul: the current <ul> in the Array of <ul> elements,
// index: the index of the current <ul> in the Array
// of <ul> elements.

// here if the index is exactly equal to 0, we add the
// 'test' class-name, otherwise we add an empty string:
(ul, index) => ul.classList.add( index === 0 ? 'test' : '' )
);

引用文献:

关于javascript - 如何按类获取可见元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42930731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com