最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Query selector an element with parent id and child class mixed - Stack Overflow

programmeradmin1浏览0评论

Example:

<div id="dataTableColToggler">
<a class="toggle-vis col0" data-column="0" >Col 0</a> - 
<a class="toggle-vis col1" data-column="1" >Col 1</a> - 
<a class="toggle-vis col2" data-column="2" >Col 2</a>
</div>

How can i get the element Col 1 with querySelector?

Example:

<div id="dataTableColToggler">
<a class="toggle-vis col0" data-column="0" >Col 0</a> - 
<a class="toggle-vis col1" data-column="1" >Col 1</a> - 
<a class="toggle-vis col2" data-column="2" >Col 2</a>
</div>

How can i get the element Col 1 with querySelector?

Share Improve this question edited May 31, 2018 at 13:50 asked May 16, 2018 at 11:11 user9324524user9324524 3
  • 1 you can not put tow classes attribute in one tag – לבני מלכה Commented May 16, 2018 at 11:17
  • All of those links only have one class, toggle-vis. You can not repeat HTML attributes on an element! – C3roe Commented May 16, 2018 at 11:18
  • I forgot that that, thanks – user9324524 Commented May 16, 2018 at 11:30
Add a ment  | 

3 Answers 3

Reset to default 3

If you need the Col 1, you should use:

var col2 = document.querySelector("#dataTableColToggler .col1");

But you should not duplicate the class attribute. Use the classes as given below:

var col2 = document.querySelector("#dataTableColToggler .col1");
console.log(col2.innerHTML);
<div id="dataTableColToggler">
  <a class="toggle-vis col0" data-column="0">Col 0</a> -
  <a class="toggle-vis col1" data-column="1">Col 1</a> -
  <a class="toggle-vis col2" data-column="2">Col 2</a>
</div>

DO NOT put tow classes attribute in one tag
Learn about class attribute here:https://www.w3schools./tags/att_global_class.asp

var col2 = document.querySelector("#dataTableColToggler .col2");
console.log(col2);
<div id="dataTableColToggler">
<a class="toggle-vis col0" data-column="0">Col 0</a> - 
<a class="toggle-vis col1" data-column="1">Col 1</a> - 
<a class="toggle-vis col2" data-column="2">Col 2</a>
</div>

You can use the .innerText() method to access the value of the col.

You've made a mistake specifying twice the keyword class=""


Look at the following snippet :

var col2 = document.querySelector("#dataTableColToggler .col2").innerText;

console.log(col2);
<div id="dataTableColToggler">
  <a data-column="0" class="toggle-vis col0">Col 0</a> -
  <a data-column="1" class="toggle-vis col1">Col 1</a> -
  <a data-column="2" class="toggle-vis col2">Col 2</a>
</div>

发布评论

评论列表(0)

  1. 暂无评论