检查子元素是否没有特定的类?

时间:2014-05-19 00:30:03

标签: javascript css class children getelementsbyclassname

我试图找出子元素是否没有特定的类。

我的元素如下:

<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>

包含g的{​​{1}}元素没有id="note1"的任何子元素。带有class="interval"的{​​{1}}元素可以。我正在尝试使用以下javascript来确定元素是否具有g的子元素:

id="note2"

我收到的错误消息是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 } }

根据this example,代码应返回具有我想要的类的所有元素,这些元素位于我指定的id的元素下。关于我做错了什么或者我可能会尝试哪些替代方案的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以使用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'*/
 }