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

Asked

Viewed 86 times

1

Good afternoon, I’m developing a pure javascript modal. What happens is the following... the script detects that there are tags with the class "modal"<div class="modal">, and when it finds one or more it inserts the tags with the classes already defined. What happens... one of the functions inserts a div into that div with the following class<div class="modal loading"></div> and so it enters as one more item within the javascript loop.
Is there any way to select only the modal that has no other 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 that way.

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

2 answers

1


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

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>

  • The answer is almost perfect, just a question, there is some way in querySelectorAll to select exactly that one class instead of passing the :not parameter()?

  • @김무진 Selecting only . modal?

  • Sorry I was implementing the code adapting the thing forgot to inhibit the previous, it solved my problem

0

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

.modal:not(.loading){

}
  • My problem is the selection in javascript not in CSS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.