【问题标题】:How to Get Element From Path Not Class or Id如何从路径而不是类或 ID 中获取元素
【发布时间】:2013-09-25 14:16:26
【问题描述】:

我正在努力寻找答案,我想要一种方式来谈论一个元素,但由于我要添加的系统,我不能通过它的 ID 来引用它,因为它是动态的。我可以指定其包含 div 的类名...本质上,我正在寻找的内容类似于:

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

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

谢谢你们!

【问题讨论】:

  • document.querySelector[All]()
  • 谢谢伙计们,这一切都是为了知道在哪里看嘿..?但我能做吗 - querySelector(div.ContainerDiv td tr p)?还是只是 querySelector(div.containerDiv)?

标签: javascript dom css-selectors


【解决方案1】:

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

示例 HTML

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

JS

获取单个元素

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

对于多个元素

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

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

【讨论】:

  • 我收到错误Uncaught TypeError: document.querySelector(...).click is not a function
  • @prabhav 你的意思是querySelectorAll().click is not a function,因为querySelector 只返回dom 元素或null,如果它返回null,你会得到不同的错误信息。如果您的意思是querySelectorAll,那是因为它返回一个集合(是否找到任何元素)并且它没有click 方法,您需要访问集合中的各个项目以访问它们的@987654337 @方法,例如querySelectorAll(...)[1].click()
  • 不,我刚刚使用了document.querySelector(...).click ,这是我收到的错误消息,我只是复制粘贴错误
猜你喜欢
  • 1970-01-01
  • 2014-05-29
  • 2012-08-06
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 2011-04-06
相关资源
最近更新 更多