You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript访问第二个ul元素并修改其CSS样式

获取.login容器下的第二个ul元素的几种方法

根据你的HTML结构,这里提供几种可靠的方式获取第二个无类名的ul元素,之后就能像操作第一个ul一样切换类来控制显示隐藏:

方法1:使用CSS选择器直接定位

利用querySelector结合:nth-child(2)或:last-child选择器(如果.login下只有两个ul,:last-child更灵活):

// 定位第二个ul
const secondUl = document.querySelector('.login ul:nth-child(2)');

// 或者如果确定是最后一个ul,用这个更稳妥
const secondUl = document.querySelector('.login ul:last-child');

方法2:通过父元素的子元素集合获取

先获取.login容器,再从它的children集合中取第二个元素(索引从0开始,第二个元素索引为1):

const loginContainer = document.querySelector('.login');
const secondUl = loginContainer.children[1];

方法3:获取所有ul后取第二个

用querySelectorAll获取.login下的所有ul,再通过索引取第二个:

const allUls = document.querySelectorAll('.login ul');
const secondUl = allUls[1];

类切换示例

获取到元素后,即可执行和第一个ul相同的类切换操作,比如:

// 切换postLogin类(根据你的逻辑调整)
secondUl.classList.toggle('postLogin');

// 或者移除/添加指定类
secondUl.classList.remove('preLogin');
secondUl.classList.add('postLogin');

内容的提问来源于stack exchange,提问作者Sergio González

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:40:30