javascript - Get specific attribute value from multiple divs with same classname on page load jquery
问题描述
I have a webpage with HTML something like this. I want to hide the background from the class swatch-option, and render the option-label in the div.
But I am not able to get the option-label.
$(document).ready(function() {
if ($('div.swatch-option').hasClass('color')) {
console.log($(this).attr('option-label'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="swatch-attribute swatch-layered color" attribute-code="color" attribute-id="93">
<div class="swatch-attribute-options clearfix">
<a href="#" aria-label="Black" class="swatch-option-link-layered">
<div class="swatch-option color " tabindex="-1" option-type="1" option-id="49" option-label="Black" option-tooltip-thumb="" option-tooltip-value="#000000" style="background: #000000 no-repeat center; background-size: initial;"></div>
</a>
<a href="#" aria-label="Red" class="swatch-option-link-layered">
<div class="swatch-option color " tabindex="-1" option-type="1" option-id="50" option-label="Red" option-tooltip-thumb="" option-tooltip-value="Red" style="background: Red no-repeat center; background-size: initial;"></div>
</a>
</div>
</div>
This is the code I am trying. But it displays undefined. There are many more divs on the page with class = "swatch-attribute swatch-layered"
, and similarly many more divs with classes swatch-attribute-options
and swatch-option
. So it is a bit complicated. Can anyone help me to get the value so that I disable the background and put value equals to option label
解决方案
Try with:
$('div.swatch-option.color').each(function() {
console.log($(this).attr('option-label'));
});
With above snippet, you'll get all divs with classes .swatch-option
and .color
- then iterate over them and access their attributes with $(this)
.
推荐阅读
- node.js - 向graphql服务器发布请求没有响应
- mysql - 需要使用 Hive HQL 忽略列表列中的最后两个值
- php - 如何在没有身份验证的情况下通过公共频道中的 laravel-echo-server 获取实时流量
- java - 使用按钮 (GUI) 运行 JAVA 程序
- sql-server - 需要游标来读取提供的参数或所有记录,但不会读取所有
- javascript - Cheerio:获取普通 + 文本节点
- python - 使用熊猫解析时间到时间戳
- shell - Shell 脚本 - 从 CSV 文件计算记录中的分隔符
- c# - ASP.NET C#中每一行的data_ItemDataBound的foreach语句
- python - 消费者可以从存储特定键值数据的分区中读取记录吗?