admin管理员组文章数量:1420213
I have a div with 3 classes, the third class (dynamic) changes
<div class="one two dynamic">test</div>
I need to select the element with class names 'one', 'two' and have a 3rd class name of any name.
I've tried using document.querySelector('.one.two.*')
- note the *
Any suggestions
edit: there are actually 5 classes and the third one (dynamic) is dynamically generated. Sorry, I should have stated that originally as I appreciate that plicates the problem...
I have a div with 3 classes, the third class (dynamic) changes
<div class="one two dynamic">test</div>
I need to select the element with class names 'one', 'two' and have a 3rd class name of any name.
I've tried using document.querySelector('.one.two.*')
- note the *
Any suggestions
edit: there are actually 5 classes and the third one (dynamic) is dynamically generated. Sorry, I should have stated that originally as I appreciate that plicates the problem...
Share Improve this question edited Sep 8, 2015 at 18:56 user2677034 asked Sep 8, 2015 at 18:22 user2677034user2677034 6941 gold badge12 silver badges22 bronze badges 2-
1
Why can't you just use
document.querySelector('.one.two')
? – rnevius Commented Sep 8, 2015 at 18:24 - 2 @rnevius, becuase his requirement may be that there must be a third class, whatever class that is – AmmarCSE Commented Sep 8, 2015 at 18:25
2 Answers
Reset to default 5You can:
- Use
querySelectorAll
to get all the elements with the classesone
andtwo
. - Borrow
filter
to create an array with only those which have exactly 3 classes. - Get the first element in that array.
[].filter.call(document.querySelectorAll('.one.two'), function(el) {
return el.classList.length == 3;
})[0];
[].filter.call(document.querySelectorAll('.one.two'), function(el) {
return el.classList.length == 3;
})[0].style.background = 'orange';
<p class="one two">one two</p>
<p class="one two three four">one two three four</p>
<p class="one two three">one two three</p>
<p class="one two three">one two three</p>
Big thanks to Oriol who pointed me in the right direction! Using his example I came up with this which returns the element with class "one two dynamic four five":
<body>
<p id="a" class="one two">a</p>
<p id="b" class="one two dynamic four five">b</p>
<p id="c" class="one two dynamic">c</p>
<p id="d" class="one two dynamic">d</p>
<script>
[].filter.call(document.querySelectorAll('.one.two'), function(el) {
if(el.classList.toString().indexOf('four five') != -1){
alert('id='+el.id);
return el;
}
})[0].style.background = 'orange';
</script>
</body>
本文标签: javascriptdocumentquerySelector with dynamic class nameStack Overflow
版权声明:本文标题:javascript - document.querySelector with dynamic class name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745325139a2653555.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论