admin管理员组文章数量:1406177
I'm trying to get the div element that's nested deep within another div, but can't get the CSS Selector string to work.
The div I want does not have a unique identifier, but resides deep within another div that has. I've gotten that top level div, but have no clue how to get the nested one.
DOM:
var obj = document.body.querySelector('.qvobject[data-qlikobjectid="XFvnjF"]');
console.log(obj);
var cont = obj.querySelector('.kpi-value');
console.log(cont);
<div class="qvobject" data-qlikobjectid="XFvnjF">
<div>
<div>
<div class="kpi-value">I WANT THIS</div>
</div>
</div>
</div>
I'm trying to get the div element that's nested deep within another div, but can't get the CSS Selector string to work.
The div I want does not have a unique identifier, but resides deep within another div that has. I've gotten that top level div, but have no clue how to get the nested one.
DOM:
var obj = document.body.querySelector('.qvobject[data-qlikobjectid="XFvnjF"]');
console.log(obj);
var cont = obj.querySelector('.kpi-value');
console.log(cont);
<div class="qvobject" data-qlikobjectid="XFvnjF">
<div>
<div>
<div class="kpi-value">I WANT THIS</div>
</div>
</div>
</div>
The result is that "obj" is the right object, but "cont" is null, so it can't find it.
Share Improve this question edited Apr 12, 2018 at 8:48 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Apr 12, 2018 at 8:43 OverrideOverride 2981 gold badge5 silver badges14 bronze badges 5- 2 your code, in snippet working, right? – Durga Commented Apr 12, 2018 at 8:47
- 3 Yeah even without running the snippet that's now been added I can't see how cont could possibly be null in that situation. – BoltClock Commented Apr 12, 2018 at 8:49
- 2 Seems like you can't reproduce the issue in your question. – Terry Commented Apr 12, 2018 at 8:52
- Yes it seems to be working here. I can't replicate with this code, because it is "thinned down". My DOM tree is bigger and with different data. It seems I need to review the structure itself, if this works. – Override Commented Apr 12, 2018 at 8:58
- Check for nested frames or shadowdom. It should work otherwise . – Nish26 Commented Apr 12, 2018 at 9:31
1 Answer
Reset to default 2You can select it using the descendent binator. Just put a space between the parent selector and the child selector.
This makes the traverser go further to any level in the dom to select the desired element.
var element = document.querySelector('.qvobject[data-qlikobjectid="XFvnjF"] .kpi-value');
console.log(element);
<div class="qvobject" data-qlikobjectid="XFvnjF">
<div>
<div>
<div class="kpi-value">I WANT THIS</div>
</div>
</div>
</div>
本文标签: javascriptquerySelector syntax for nested elementsStack Overflow
版权声明:本文标题:javascript - querySelector syntax for nested elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744356635a2602337.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论