【问题标题】:JS how to access element with id beginning with underscore "_"?JS如何访问id以下划线\"_\"开头的元素?
【发布时间】:2022-11-30 06:26:52
【问题描述】:

我想在我网页中嵌入的 YouTube 订阅按钮上进行一种点击重定向(用户点击 span,另一个元素以编程方式获取 .click()ed)。 在 Google 的脚本运行初始标记后,标记如下(简化):

<!-- The property `otherproperties="notmentionedhere"` is a placeholder for the other properties those elements have, some of those properties vary with each load of the page. -->
<div id="___ytsubscribe_0" otherproperties="notmentionedhere">
    <iframe otherproperties="notmentionedhere">
        #document <!-- This element doesn't really exist, it's Firefox's way of representing the markup inside the iFramed page in DevTools -->
            <!--some other elements-->
                <button data-channel-external-id="UCO6YRllfXXIe2lPWenjmfPw" otherproperties="notmentionedhere"><!-- some other elements /--></button>
            <!--/some other elements-->
</div>

我当前在 span 的 onclick 属性中单击该按钮的代码:

document.getElementById('___ytsubscribe_0').querySelector('iframe').contentWindow.document.querySelector('button[data-channel-external-id=UCO6YRllfXXIe2lPWenjmfPw]').click();

我遇到的问题是元素的 ID 属性必须以字母开头,但 YouTube 订阅按钮的容器 ID 以三个下划线开头。

这是显示实际标记加上我的代码的代码 sn-p:

<!-- You might have to copy the markup into an own HTML document on your computer to see it in action, at least for me it always fails on load with a "SecurityError: Document.cookie getter: Forbidden in a sandboxed document without the 'allow-same-origin' flag."... -->
<span onclick="document.getElementById('___ytsubscribe_0').querySelector('iframe').contentWindow.document.querySelector('button[data-channel-external-id=UCO6YRllfXXIe2lPWenjmfPw]').click();">Click here to subscribe!</span>
<script src="https://apis.google.com/js/platform.js"></script>
<div class="g-ytsubscribe" id="yt-sub-dark" data-channelid="UCO6YRllfXXIe2lPWenjmfPw" data-layout="full" data-theme="dark" data-count="default"></div>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    你可以使用Document.querySelector()

    请参见下面的 sn-p。

    const ytsubdiv = document.querySelector('#___ytsubscribe_0')
    
    console.log(ytsubdiv)
    &lt;div id="___ytsubscribe_0" otherproperties="notmentionedhere"&gt;hello&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      相关资源
      最近更新 更多