2016-07-27 139 views
0

我有一個滑塊,並在滑動我試圖獲取中心元素的屬性值。我的js似乎不起作用。通過父類名獲取屬性值

owl.on('changed.owl.carousel', function(event) { 
 
    var a = document.getElementsByClassName("owl-item active center").children("item").attr("data-price"); 
 
    console.log(a); 
 
});
<div class="owl-item active center" style="width: 340px; margin-right: 0px;"> 
 
    <div class="item" data-price="200" data-name="Car 2" data-color="Green"> 
 
    </div> 
 
</div>

+2

'兒童()','上()'等。是jQuery方法 –

+0

我認爲'孩子'也可以在JavaScript中使用。它只返回元素的子節點,而'childNodes'返回元素和文本節點。 –

+1

@MohitBhardwaj:'children'屬性不是js情況下的一種方法,你也不能將它應用於nodeList –

回答

2

看來,下面children超過一個方法的屬性:

document.getElementsByClassName("owl-item active center")[0].children 

,因此你不能用它作爲一種方法。

除此之外有沒有這樣的東西作爲attr - 您可以使用例如:

domElement.getAttribute("class") 
0

.children是一個只讀屬性,返回節點的子元素的現場HTMLCollection

所以,爲了選擇具有特定類的元素,您需要驗證每個單獨的子節點,然後返回該子節點的屬性。

示例代碼:

// pEl is a reference to a <p> element 
var elementChildren = pEl.children; 
for (var i = 0; i < elementChildren.length; i++) { 
    console.log(elementChildren[i].tagName); 
    // NOTE: elementChildren is a live list, adding or removing children from pEl 
    // will change the members of elementChildren immediately 
} 

pEl.children是的HTMLCollection,這是elementNodeReference的孩子DOM元素的有序集合。如果不存在子元素,然後elList不包含任何元素和具有爲0

參考長度:ParentNode.Children from MDN