简体   繁体   English

如何选择具有动态ID的父元素的嵌套子元素?

[英]How can I select a nested child element of a parent element that has a dynamic ID?

I'm currently toying around with Zendesk, and trying to make changes to a text element on the page. 我目前正在玩Zendesk,并尝试更改页面上的text元素。 Sadly, Zendesk's elements are dynamic enough that the name of the main element will change on each page load. 可悲的是,Zendesk的元素具有足够的动态性,以至于每次加载页面时主元素的名称都会改变。

Thankfully the structure of the element trees stay pretty static, but it's only the parent element's name that's changing: 幸运的是,元素树的结构保持非常静态,但是只有父元素的名称在变化:

#ember6030 > div.comment > div > p
#ember3483 > div.comment > div > p

Currently, here's where I'm at so far: 目前,这是我到目前为止的位置:

var item = document.querySelectorAll("[name^=ember] > div.comment > div > p");
var itemtext = item.innerHTML;
console.log(itemtext);

I'm sure I'm missing something, but wouldn't my selector var be correct? 我确定我遗漏了一些东西,但是我的选择器var不正确吗?

Something like finding an element that begins with "ember" but then follows the rest of the parent-child tree just fine. 就像找到一个以“ ember”开始但随后跟随父子树其余部分的元素一样。


EDIT: Things are being a bit more stubborn than I thought, but I've got some extra details if this helps: For the div.comment > div > p elements, a handful of those load up. 编辑:事情比我想象的要更加顽固,但是如果有帮助,我还有一些额外的细节:对于div.comment > div > p元素,其中的一些加载。 For right now, I'd like to try targeting just one, but if I can get the text contents of all these elements in console messages, that'd be awesome. 现在,我只想尝试定位一个,但是如果我能在控制台消息中获得所有这些元素的文本内容,那就太好了。

For those CSS paths you would use: 对于这些CSS路径,您将使用:

var item = document.querySelector("[id^=ember] > div.comment > div > p");
var itemtext = item.textContent;
console.log(itemtext);

since # is the CSS selector for the id attribute, not the name . 因为#id属性的CSS选择器,而不是name

See also David Klinge's answer about NodeLists. 另请参阅David Klinge关于NodeLists 的答案

So the final code is: 所以最终的代码是:

var items = document.querySelectorAll("[id^=ember] > div.comment > div > p");
items.forEach (item => {
  var itemtext = item.textContent;
  console.log(itemtext);
} );

Finally, for what you seem to be trying to do, you probably want textContent instead of innerHTML . 最后,对于您似乎想做的事情,您可能需要textContent而不是innerHTML This avoids false hits on attributes, comments, etc. 这样可以避免对属性,注释等的错误点击。

document.querySelectorAll returns a NodeList that must be iterated over. document.querySelectorAll返回必须迭代的NodeList You should be able to use a forEach to iterate over the elements querySelectorAll selects. 您应该能够使用forEach遍历querySelectorAll选择的元素。

var items = document.querySelectorAll("[id^=ember] > div.comment > div > p");
items.forEach (item => {
  var itemtext = item.textContent;
  console.log(itemtext);
} );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM