首页 > 解决方案 > 使用javascript获取属性值

问题描述

这是我的代码,

var selectedLabel = $(".alllabel li.active").attr("id");

我试过了

    var selectedLabel = parent.document.getElementsByClassName(".alllabel li.active")
                       .getAttribute("id");

但是未定义的值得到了。请帮我离开这里..!

标签: javascriptcodeigniter-3

解决方案


如果您的问题是如何做与您直接使用 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.


推荐阅读