javascript - 使用javascript获取属性值
问题描述
这是我的代码,
var selectedLabel = $(".alllabel li.active").attr("id");
我试过了
var selectedLabel = parent.document.getElementsByClassName(".alllabel li.active")
.getAttribute("id");
但是未定义的值得到了。请帮我离开这里..!
解决方案
如果您的问题是如何做与您直接使用 DOM 显示的 jQuery 代码相同的事情,最简单的方法是:
var selectedLabel = document.querySelector(".alllabel li.active").id;
querySelector
查找 DOM 中与给定 CSS 选择器匹配的第一个元素,并且该id
属性有一个名为id
.
现场示例:
var selectedLabel = document.querySelector(".alllabel li.active").id;
console.log(selectedLabel);
<ul class="alllabel">
<li id="not-active">not-active</li>
<li class="active" id="the-active-one">the active one</li>
</ul>
但是,与使用 jQuery 的代码不同,如果根本找不到该元素,则会引发错误。如果你想得到undefined
(这是 jQuery 在这种情况下会给你的),你可以这样做:
var element = document.querySelector(".alllabel li.active");
var selectedLabel = element ? element.id : undefined;
或者使用 ES2021 的可选链操作符:
const selectedLabel = document.querySelector(".alllabel li.active")?.id;
那会给你,null
而不是undefined
如果没有找到,但是......足够接近。如果您真的非常想要undefined
,您还可以使用 ES2021 的无效合并运算符:
const selectedLabel = document.querySelector(".alllabel li.active")?.id ?? undefined;
如果您想获取没有反射属性的属性的值,您可以getAttribute
在问题中使用 as 。例如,这是此答案中的第一个代码块,getAttribute
而是使用:
var selectedLabel = document.querySelector(".alllabel li.active").getAttribute("id");
但同样,您不需要使用id
.
推荐阅读
- javascript - 如果javascript中的href为空,如何禁用锚标记
- python - 数据框中条形图形式值的颜色?
- laravel - 在 laravel 门中总是返回 false
- powerbi - PowerBI Premium 连接服务器分析服务
- erlang - 函数列表中的异常错误:foldl/3(lists.erl,第 1263 行)
- javascript - 如何从 Rust 函数获取字节到 JavaScript?
- flutter - 颤振从 CarouselSlider 中移除左侧间隙
- navigation - SwiftUI:使用 .onTapGuesture{} 导航到另一个视图
- mysql - 将字符串相似度与大量记录进行比较
- c# - 使用对象复活处理非托管资源的共享所有权