简体   繁体   English

通过父类名称获取属性值

[英]Getting attribute value by parent class name

I have a slider, and on swipe I am trying to get the attribute value of the centered element. 我有一个滑块,在滑动时,我试图获取居中元素的属性值。 my js doesn't seem to work. 我的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> 

It seems that the below children is more of a property than a method: 似乎下面的children元素更多是属性而不是方法:

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

hence you cannot use it as a method. 因此您不能将其用作方法。

Besides that there's not such thing as attr - you can use for ex: 除此之外,没有attr这样的东西-您可以用于ex:

domElement.getAttribute("class")

.children is a read-only property that returns a live HTMLCollection of the child elements of Node. .children是只读属性,它返回Node的子元素的实时HTMLCollection

so in order to select the element with specific class you need to verify every single child node and then return attribute of that child node. 因此,为了选择具有特定类的元素,您需要验证每个单个子节点,然后返回该子节点的属性。

Sample Code: 样例代码:

// 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 is a HTMLCollection, which is an ordered collection of DOM elements that are children of elementNodeReference. pEl.children是HTMLCollection,它是DOM元素的有序集合,这些元素是elementNodeReference的子级。 If there are no element children, then elList contains no elements and has a length of 0. 如果没有子元素,则elList不包含任何元素,且长度为0。

Reference : ParentNode.Children from MDN 参考: 来自MDN的ParentNode.Children

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM