Home > Net >  Printing value of custom attributes on multiple divs
Printing value of custom attributes on multiple divs

Time:11-19

I am working on a Shopify store where there are multiple divs like below:

<div  data-variant-option="" data-variant-option-index="0" data-variant-option-chosen-value="One"></div>

<div  data-variant-option="" data-variant-option-index="0" data-variant-option-chosen-value="Two">

<div  data-variant-option="" data-variant-option-index="0" data-variant-option-chosen-value="Three">

<div  data-variant-option="" data-variant-option-index="0" data-variant-option-chosen-value="Four">

I want to get the value of custom attribute data-variant-option-chosen-valueand print that into <span ></span>

I tried reading the custom attribute value by following jQuery without any success

$(document).ready(function() {
$('.options-selection__option-values').each(function() {
  console.log($(this).attr('data-variant-option-chosen-value'));
});

CodePudding user response:

Get the value of attribute using $(this).attr("data-variant-option-chosen-value"), concatenate it, set it to the required target.

Also your template and script has some errors. divs missing closing tag and the $(document).ready(function () { missing the cloaing tag

$(document).ready(function () {
  let val = ''
  $(".options-selection__option-values").each(function () {
    val  = $(this).attr("data-variant-option-chosen-value");
  });
  $(".selected-variant").text(val)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<span ></span>
<div
  
  data-variant-option=""
  data-variant-option-index="0"
  data-variant-option-chosen-value="One"
></div>

<div
  
  data-variant-option=""
  data-variant-option-index="0"
  data-variant-option-chosen-value="Two"
></div>

<div
  
  data-variant-option=""
  data-variant-option-index="0"
  data-variant-option-chosen-value="Three"
></div>

<div
  
  data-variant-option=""
  data-variant-option-index="0"
  data-variant-option-chosen-value="Four"
></div>

CodePudding user response:

It works just fine, you just have syntax error, you are missing "})" at the end and it throws the error Uncaught SyntaxError: Unexpected end of input"

As of now, you are not closing neither the anonymous callback function, neither the ready function.

$(document).ready(function() {

$('.options-selection__option-values').each(function() {
  console.log($(this).attr('data-variant-option-chosen-value'));
});
})
  • Related