如何使用querySelector()获取具有重复ID的div? [英] How to get the div that has a duplicated id using querySelector()?

查看:62
本文介绍了如何使用querySelector()获取具有重复ID的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a <div> and a <video> that both have the same id:

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

我无法更改div或视频的ID.div由 video.js 库自动创建,该库为div和视频元素赋予相同的ID.

It is not possible for me to change the IDs of the div or the video. The div is created automatically by the video.js library, which gives both the div and the video elements the same id.

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

How do I target the div element alone? (Using querySelector() or similar)

推荐答案

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

You can prefix the id name with the element, but don't do this - correct your badly formed HTML instead.

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>

这篇关于如何使用querySelector()获取具有重复ID的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆