How to select only the class without the daughter class in pure javascript

1

Good afternoon, I'm developing a modal in pure javascript. What happens is the following ... the script detects that there are tags with the "modal" class <div class="modal"> , and when it finds one or more it inserts the tags with the already defined classes. What happens ... one of the functions inserts a div within this div with the following class <div class="modal loading"></div> and in that way it enters as one more item inside the javascript loop.
Is there any way to select only the modal that does not have another class inside?
I'm using this call in my javascript

var modal = document.getElementsByClassName('modal');
modal[i].innerHTML = "<div class='modal loading'></div>"

My CSS is this way.

    .modal>.loading {
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 10%;
    background: url(loader.gif) center no-repeat;
}
    
asked by anonymous 19.01.2018 / 22:55

2 answers

1

You can detect using querySelector , which will return false if there is no div with the class you are looking for.

  

The advantage of using querySelectorAll instead of    getElementsByClassName is that the first allows CSS selectors   complete.

// aqui selecione apenas as divs com .modal sem .loading
var modal = document.querySelectorAll('div.modal:not(.loading)');

for(var item of modal){
   if(!item.querySelector("div.loading")){ // verifica se a div com a classe .loading existe dentro da modal
      console.log('A '+item.innerText+' não possui ".loading"');
   }
}
/* Estilos apenas para ilustração */
div.modal:not(.loading){
   display: block;
   width: 100px;
   margin: 10px 0;
   background: red;
}
<div class="modal">
   <div class="modal loading">Loading</div>
   modal 1
</div>
<div class="modal">
   modal 2
</div>
<div class="modal">
   modal 3
</div>
<div class="modal">
   <div class="modal loading">Loading</div>
   modal 4
</div>
    
19.01.2018 / 23:13
0

You can use the :not() pseudo selector, in your case, not to select the .loading class you can use this selector:

.modal:not(.loading){

}
    
19.01.2018 / 23:14