Christopher Gaston Christopher Gaston - 1 month ago 6
CSS Question

Check if a child element does not have a specific class?

I am trying to find if a child element does not have a specific class.

My elements are as follows:

<g id="note1">
<path id="Barline1" d="M55.837,19.278h0.249c0.11,0,0.199,0.089,0.199,0.199V40.56c0,0.11-0.089,0.199-0.199,0.199h-0.249c-0.11,0-0.199-0.089-0.199-0.199V19.478C55.638,19.368,55.727,19.278,55.837,19.278z"/>
<path class="root" d="M54.113,38.945c1.116,0,2.172,0.578,2.172,1.813c0,1.435-1.116,2.411-2.052,2.969c-0.717,0.418-1.514,0.717-2.331,0.717c-1.116,0-2.172-0.578-2.172-1.813c0-1.435,1.116-2.411,2.052-2.969C52.499,39.244,53.296,38.945,54.113,38.945z"/>
</g>
<g id="note2">
<path id="BarLine2" d="M70.852,16.788h0.249c0.11,0,0.199,0.089,0.199,0.199v21.082c0,0.11-0.089,0.199-0.199,0.199h-0.249c-0.11,0-0.199-0.089-0.199-0.199V16.987C70.653,16.877,70.742,16.788,70.852,16.788z"/>
<path class="root" d="M69.127,36.454c1.116,0,2.172,0.578,2.172,1.813c0,1.435-1.116,2.411-2.052,2.969c-0.717,0.418-1.514,0.717-2.331,0.717c-1.116,0-2.172-0.578-2.172-1.813c0-1.435,1.116-2.411,2.052-2.969C67.513,36.753,68.31,36.454,69.127,36.454z"/>
<path class="interval third" d="M69.127,31.473c1.116,0,2.172,0.578,2.172,1.813c0,1.435-1.116,2.411-2.052,2.969c-0.717,0.418-1.514,0.717-2.331,0.717c-1.116,0-2.172-0.578-2.172-1.813c0-1.435,1.116-2.411,2.052-2.969C67.513,31.772,68.31,31.473,69.127,31.473z"/>
</g>


The
g
element with
id="note1"
does not have any child elements with
class="interval"
. The
g
element with
id="note2"
does. I'm trying to use the following javascript to determine if an element does not have a child element with
class="interval"
:

for(var n=0;n<document.getElementsByClassName('root').length;n++){
if(document.getElementById('note'+(n+1)).getElementsByClassName('interval') ){
//some child element has class
} else {
//no child element has class
}
}


I'm getting the error message that the property or method
document.getElementsByClassName
is not supported on both
g
elements.

According to this example, the code should return all the elements with the class I want which are under the element of the id I specified. Any ideas on what I am doing wrong or what alternatives I might try?

Answer

You can use element.querySelectorAll() :

 if(document.getElementById('note'+(n+1)).querySelectorAll('.interval').length > 0){
     /*There are elements with CSS class 'interval'*/
 }
 else{
     /*There are no elements with CSS class 'interval'*/
 }