首页 > 解决方案 > 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

标签: javascriptjqueryhtml

解决方案


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


推荐阅读