Search code examples
javascripthtmljqueryattr

How to html text show as par this attribute in jQuery?


The problem is not shown in each tag. I face some issues like this: attr is not a function.

$('document').ready(function() {
  jQuery('.custom-size .size .text').each(function() {
    var option_label = this.attr("option-label");
    jQuery(this).text(option_label);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="custom-size">
  <div class="size">
    <div class="text" option-label="NONE"></div>
    <div class="text" option-label="44">NONE</div>
    <div class="text" option-label="46">44</div>
    <div class="text" option-label="48">46</div>
  </div>
</div>


Solution

  • a) Since you are using the latest version of jQuery use $ instead of jQuery

    b) You need to use $(this) instead of this.

    c) Better to use data-attributes.

    Working sample:

    $('document').ready(function() {
      $('.custom-size .size .text').each(function() {
        var option_label = $(this).data("option-label");
        $(this).text(option_label);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <div class="custom-size">
      <div class="size">
        <div class="text" data-option-label="NONE"></div>
        <div class="text" data-option-label="44">NONE</div>
        <div class="text" data-option-label="46">44</div>
        <div class="text" data-option-label="48">46</div>
      </div>
    </div>