如何使用 querySelector() 获取具有重复 id 的 div?

How to get the div that has a duplicated id using querySelector()?

我有一个 <div> 和一个 <video>,它们都具有相同的 ID:

<div id="id1">
    Some content
</div>
<video id="id1">
    <source></source>
</video>

我无法更改 div 或视频的 ID。 div 由 video.js 库自动创建,它为 div 和视频元素提供相同的 id。

如何单独定位 div 元素? (使用 querySelector() 或类似的)

永远不要使用一个 ID 两次。

<div id="id1">
  Some content
</div>
<video id="id2">
  <source></source>
</video>

var el = document.querySelector('#id2');

W3 Docs:

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character.

您可以在 id 名称前加上元素前缀,但不要这样做 - 改正格式错误的 HTML。

document.querySelectorAll('div#id1')

window.onload = function(){
  document.querySelectorAll("div#id1")[0].style.backgroundColor='red';
  document.querySelectorAll("video#id1")[0].style.backgroundColor='green';
}
<div id="id1">
Some content
</div>
<video id="id1">
<source></source>
</video>

ID 应该是唯一的。 specification

如果 HTML 代码是你的,你应该先解决这个问题。

另一方面,如果您在无法修改的网站上进行操作(例如用户脚本):

querySelector('div#id1'),或者,getElementById('id1') 在有重复的 id 时没有标准行为。所以你可能需要

document.querySelector('div[id="id1"]')