2017-05-29 71 views
0

我有一個HTML標籤:如何檢查「for」prop prop excists的標籤?

<label class="label-radio-button-detail-gray" for="Metallic Black"> 
</label> 

和陣列我從一個ajax交還給我:

Array [ "Metallic Black" ] 

我要檢查,如果有一個標籤=「金屬黑」在頁面上的excists然後添加一個類。

這是我有:

).done(function(response){ 
    console.log(response); 
    if(response.length > 0) { 
     response.forEach(function(item){ 

     }); 
    } 
}); 

我如何實現這一目標?

+0

'金屬Black'不是for'的'有效值:_ 「如果指定了屬性,該屬性的值必須是一個貼標籤的元素的ID」 _([W3 ](https://www.w3.org/TR/html5/forms.html#attr-label-for)),並且不允許包含空格:_「當在HTML元素上指定時,id屬性值必須在元素樹中的所有ID中必須是唯一的,並且必須至少包含一個字符。該值不能包含任何ASCII空格。「_([HTML Standard](https://html.spec.whatwg.org/multipage/dom .html#the-id-attribute)) – Andreas

回答

1

您可以使用下面的解決方案。

var response = ["Metallic Black"]; 
 

 
if (response.length > 0) { 
 
    response.forEach(function(item) { 
 
    $("label").each(function() { 
 
     if ($(this).prop("for") == item) { 
 
     $(this).addClass("your-class"); 
 
     } 
 
    }); 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 

 
<label class="label-radio-button-detail-gray" for="Metallic Black"> Metallic Black 
 
</label> 
 
<br/> 
 
<label class="label-radio-button-detail-gray" for="Metallic Black1"> Metallic Black1 
 
</label>

+0

謝謝,這太棒了! – Rubberduck1337106092

0

用jquery怎麼樣?

var label = $('label[for="Metallic Black"]').addClass("new_class"); 

var label = $('label[for="Metallic Black"]').addClass("new_class");
.new_class{ 
 
color:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label for="Metallic Black" class="">sdfsdfsf</label>

下面提供小的例子。

+0

這不檢查是否有「Metallic Blac k「 – Rubberduck1337106092

+0

@JordyGroote我更新了我的答案 –

0

純JavaScript解決方案。在ternary下面會返回truthy語句(「foo exists」),如果有dom elemnt與for="Metallic Black"屬性找到。否則它會評估foo到undefined這是錯誤的。

var foo = document.querySelector('[for="Metallic Black"]'); 
 
console.log(foo ? "foo exists" : "no entry found");
<label class="label-radio-button-detail-gray" for="Metallic Black"> 
 
</label>