1

I'm trying to manipulate css values using jquery. I want to add width to .block, using the value of it's child element.

Function doesn't work when page is loaded, but if I run it on console (chrome-dev); it works.

Here's my code:

$(document).ready(function() {
  $('.gauge').each(function() {
    var text = $(this).text();
    $(this).parent().css('width', text);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <span class="wrap"><span class="gauge ">70%</span></span>
    <span class="wrap"><span class=" gauge ">20%</span></span>
    <span class="wrap"><span class=" gauge ">10%</span></span>
  </li>
</ul>

1
  • 2
    Probably running js before page renders Commented Dec 12, 2019 at 14:39

2 Answers 2

3

It seems to be working well if you set the parents to display: block:

$(document).ready(function () {
  $('.gauge').each(function () {
    var text = $(this).text();
    $(this).parent().css('width', text);
  }); 
});
ul {
  padding: 0px;
  margin: 0px;
  display: block;
}

ul li {
  list-style: none;
  display: block;
}

.wrap {
  display: block;
  width: 100%;
  height: 30px;
  background-color: #FEFEFE;
  margin-bottom: 10px;
}
.wrap .gauge {
  display: block;
  color: white;
  padding: 5px;
  font-size: 12px;
  line-height: 20px;
}
.wrap:nth-child(1) .gauge {
  background-color: red;
}
.wrap:nth-child(2) .gauge {
  background-color: blue;
}
.wrap:nth-child(3) .gauge {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <span class="wrap"><span class="gauge ">70%</span></span>
    <span class="wrap"><span class=" gauge ">20%</span></span>
    <span class="wrap"><span class=" gauge ">10%</span></span>
  </li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

0

spans don't have a width. It works when using floating divs.

$(document).ready(function() {
  $('.gauge').each(function() {
    var text = $(this).text();
    $(this).parent().css('width', text);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="wrap" style="float:left;"><span class="gauge ">70%</span></div>
    <div class="wrap" style="float:left;"><span class=" gauge ">20%</span></div>
    <div class="wrap" style="float:left;"><span class=" gauge ">10%</span></div>
  </li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.