Search code examples
jquerycopywidth

jQuery span text copy and use as width


I am trying to copy a span text value to a html width value but i cant get it working?

With the code below i manged to duplicate the text but how can i set it as the width of the p element?

$('.duplicate').text(function() {
  return $(this).closest('ul li').find('em').text();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <p class="duplicate"></p>
    <em>100</em>
  </li>
  <li>
    <p class="duplicate"></p>
    <em>200</em>
  </li>
  <li>
    <p class="duplicate"></p>
    <em>300</em>
  </li>
</ul>


Solution

  • You need to apply the function to return the value to width(), not text():

    $('.duplicate').width(function() {
      return $(this).closest('ul li').find('em').text();
    });
    p.duplicate {
      min-height: 10px; /* just for testing */
      background-color: #CCC;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li>
        <p class="duplicate"></p>
        <em>100</em>
      </li>
      <li>
        <p class="duplicate"></p>
        <em>200</em>
      </li>
      <li>
        <p class="duplicate"></p>
        <em>300</em>
      </li>
    </ul>