为了账号安全,请及时绑定邮箱和手机立即绑定

如何读取具有 href 的 id 元素

如何读取具有 href 的 id 元素

aluckdog 2023-09-18 15:28:14
我正在尝试删除以下 id 引用的内容:<...id href="https://xyz'...>我的代码:var right = document.getElementById('https://xyz');var parent = right.parentNode;parent.removeChild(right);问题是当我引用 id 的名称时,它返回为 null。我尝试了 document.getElementById(' https://xyz ').href,但仍然为空。有什么建议么?
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

您可能想使用document.querySelector:

var right = document.querySelector('[href="https://xyz"]');

或者如果您需要n-th匹配,document.querySelectorAll:

var right = document.querySelectorAll('[href="https://xyz"]')[n];


查看完整回答
反对 回复 2023-09-18
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

首先我们要了解什么是html id属性。

定义和用法

id 属性指定 HTML 元素的唯一 id(该值在 HTML 文档中必须是唯一的)。

id 属性最常用于指向样式表中的样式,并通过 JavaScript(通过 HTML DOM)来操作具有特定 id 的元素。如何达到你的目的:

const barElement = document.getElementById('bar');//Getting the element which id is bar.

console.log(barElement);

const fooElement = barElement.parentNode;//Getting bars parent.

console.log(fooElement);

<div id="foo">

  <a id="bar" href="#"></a>

</div>


查看完整回答
反对 回复 2023-09-18
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

那是因为您没有为该标签分配任何 ID。因此 document.getElementById(' https://xyz ') 不会给你任何东西,因为没有带有此 ID 的标签。

您必须像这样分配一个 ID:

<...id="ID_of_href" href="https://xyz'...>

然后你可以通过以下方式获取它:

document.getElementById('ID_of_href')


查看完整回答
反对 回复 2023-09-18
  • 3 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信