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

javascript - document.querySelector with dynamic class name - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 5

You can:

  1. Use querySelectorAll to get all the elements with the classes one and two.
  2. Borrow filter to create an array with only those which have exactly 3 classes.
  3. 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>
发布评论

评论列表(0)

  1. 暂无评论