javascript 如何从路径而不是类或 ID 中获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18912584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:39:30  来源:igfitidea点击:

How to Get Element From Path Not Class or Id

javascriptdomcss-selectors

提问by Phish

I am struggling to find an answer for this, I want a way to talk about an element, but because of the system I am adding to I do can not reference by its Id as it is dynamic. I can specify the class name of its containing div though... In essence what I am looking for is something along the lines of:

我正在努力为此找到答案,我想要一种谈论元素的方法,但是由于我添加的系统,我无法通过其 Id 进行引用,因为它是动态的。我可以指定其包含的 div 的类名......本质上我正在寻找的是类似的东西:

var disAb=document.getElementBySomething("div.ContainerDiv select")

When I mention the term 'path' I mean how I would reference it in CSS (see code reference).

当我提到术语“路径”时,我的意思是我将如何在 CSS 中引用它(参见代码参考)。

Thank you guys!

感谢你们!

回答by Patrick Evans

You want document.querySelectoror document.querySelectorAll, then just reference it by its hierarchy path:

您想要document.querySelectoror document.querySelectorAll,然后只需通过其层次结构路径引用它:

Sample HTML

示例 HTML

<div class="ContainerDiv">
   <table>
   <tr>
      <td>
        <div>
           <select>
              <option>Some options</option>
           </select>
        </div>
      </td>
   </tr>
   </table>
</div>

JS

JS

Get single element

获取单个元素

var select=document.querySelector("div.ContainerDiv table tr td div select");
select.id = "someid";

For more than one element

对于多个元素

var selects=document.querySelectorAll("div.ContainerDiv select");
selects[0].id = "someid";

Of course you do not need each part of the hiearchy, for instance you could just use: div.ContainerDiv selector div.ContainerDiv table selectetc.

当然,您不需要层次结构的每个部分,例如您可以只使用:div.ContainerDiv selectdiv.ContainerDiv table select等。