This particular function fails to execute outside of the console and only functions properly within it

Currently, I am experimenting with modifying CSS values using jQuery. My goal is to include the width to a .block element, based on the value of its child element.

Oddly enough, the function does not seem to work when the page initially loads. However, if I execute it through the console (using Chrome DevTools), it works perfectly fine.

Below is the snippet of 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>

Answer №1

When you apply display: block to the parents, everything seems to be functioning well:

$(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>

Answer №2

spans do not inherently have a width, but they can be made to work 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you modify the primary data component in Vue2 using a separate single-file component?

Is there a way to modify the menu component in my main.js file, where the component is nested within another component? I am looking to change the menu component upon logging in. main.js var Vue = require('vue'); var VueResource = require(&apo ...

Changing the screen resolution can cause the LI elements to become disorganized and appear out of

I have a menu that displays multiple links using a styled UL. Everything looks great at 100% resolution, but when I adjust the screen resolution, the links no longer fit within the menu and some end up on another line, causing issues. My concern is this - ...

The aspect ratio of a DIV element is not maintaining its scale properly in Firefox

My current challenge involves using a Script to Scale a Div while maintaining the aspect ratio. The objective is to ensure that 100% of the DIV remains visible while maximizing its size. As you scale the browser width, the div adjusts its height to 100%, a ...

Allow foreign characters with regex while excluding special symbols

While browsing, I came across this thread: Is there a regular expression to match non-English characters?. It provides a regex to remove foreign characters using the code snippet str = str.replace(/[^\x00-\x7F]+/g, "");. My goal is slightly diff ...

Is it possible to stop slick slider from automatically scrolling when I click on the navigation slider?

I am in need of utilizing the slider syncing feature (example can be found here by scrolling down), However, I have noticed that clicking on the navigation slide causes the entire navigation to auto-slide further. My goal is to disable this function so th ...

Tips on placing a white background behind fa-3x (Font-awesome) icons

I am facing challenges while trying to customize the background behind my font-awesome icons. My goal is to create a white background that does not extend beyond the actual icon itself. Currently, the result looks like the image below: https://i.sstatic. ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

Creating unique CSS class and ID names dynamically in PHP

I have two divs with randomly generated IDs and I would like to use those IDs in my CSS instead of using inline styles. Is there a way to achieve this without creating a separate PHP file with a CSS header? For example, I want the padding for the ID $id_ ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

modify the appearance of HTML controls in real time with C#

Is there a way to dynamically add an additional navigation item to my website's menu list when the admin logs in through admin.aspx? The menu list is created using HTML controls such as <ul>...<li>, and I would like the new navigation item ...

What is the process behind executing the scripts in the jQuery GitHub repository when running "npm run build"?

Check out the jQuery repository on GitHub. Within the jQuery repo, there is a "build" folder. The readme.md mentions the npm command: npm run build This command triggers the execution of scripts in the build folder to complete the building process from ...

extract the information from a specific div on a different website using JavaScript

My goal is to load a specific div with a class="container" from a website and extract its content into my application. Upon making an ajax call to retrieve the site's data, I encountered a cross-domain origin error since I don't have access to t ...

What am I doing wrong in my Javascript or jQuery code that is causing me to constantly receive

I am facing an issue with the following HTML code snippet: <a class="tabTitle" id="title_boxtab_default" tab-type="default" href="#tabs-3">Sample</a> When using jQuery, I am attempting to retrieve the value of the href attribute using the fol ...

There are two distinct varieties of object arrays

I recently encountered an issue while trying to sort my array of Star Wars episodes by episode ID. The problem emerged when comparing two arrays: one manually inputted in the code snippet labeled as "1" on the screenshot, and the other generated dynamicall ...

Vue JS Issue: Button click does not trigger tooltip update

I am currently utilizing Vue 3 alongside Bootstrap 5.2. In my project, I have successfully implemented a tooltip by the following method: App.vue <script> import { Tooltip } from "bootstrap"; export default { mounted() { Array.from( ...

Preventing the user from using the mouse wheel until the CSS animation finishes

I am working with multiple functions that are triggered by scrolling the mouse wheel up and down. These functions must be called in a specific order, but the issue arises when users scroll quickly causing the CSS animations from the previous function to ...

Troubleshooting a Safari bug with element.click()

When the 'subButton2' button is clicked, the 'uploadBtn'(display:none;) should also be clicked. This functionality needs to work across different browsers: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_html_click The cod ...

Nested table with combined ng-repeat

When working with AngularJs in a web app, I encountered a challenge involving a large array containing two groups of objects, each with a sub-array. My goal was to display a table where the first row shows the foodName and totalCount, which is the sum of a ...