Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements?

Here is my code:

.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<ul class="navbar-items">
  <li><a>one</a></li>
  <li><a>two</a></li>
</ul>

<ul class="navbar-items hidden">
  <li><a>one</a></li>
  <li><a>two</a></li>
</ul>

<script type="text/javascript">
  $(".navbar-items > li > a").each(function(index) {
    console.log(this);
    var thisWidth = $(this).outerWidth(true);
    console.log(thisWidth);
  });
</script>

Result:

<a>​one​</a>​
25
<a>​two​</a>​
26
<a>​one​</a>​
2
<a>​two​</a>​
2

Expected result:

<a>​one​</a>​
25
<a>​two​</a>​
26
<a>​one​</a>​
25
<a>​two​</a>​
26

Any suggestions on how to get the width of these hidden elements?

UPDATE:

I managed to retrieve the width of the hidden element by doing this:

<a class="show">Hello World</a>
<a class="hidden">Hello World</a>

console.log($('.show').outerWidth(true));
console.log($('.hidden').outerWidth(true));

Result:

81
81

How come?

Answer №1

If you want to accomplish something a bit unconventional, you can try a workaround by duplicating an element and hiding it from view. Once it has been added to the document object model (DOM), we can delete it once its width has been captured.

var appHook = $('body');

$(".navbar-items > li > a").each(function(index) {
  var element = $(this).clone();
  element.css({ visibility: 'hidden' });
  appHook.append(element);
  console.log(element.outerWidth());
  element.remove();
});
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<ul class="navbar-items">
  <li><a>one</a></li>
  <li><a>two</a></li>
</ul>
<ul class="navbar-items hidden">
  <li><a>one</a></li>
  <li><a>two</a></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

Employing jQuery for element rotation via swipe/drag movements

I am looking to create a dynamic experience where a circle rotates in sync with the user's swipe or drag gestures on the screen. Currently, I am developing an app using Phonegap and considering integrating hammer.js as it comes highly recommended by m ...

Discover the myriad of possibilities created by combining arrays

I am working on a code snippet that aims to generate an array containing all possible combinations between two or more arrays. However, I am encountering a specific issue. getCombn(arr: string | any[], pre?: string | undefined) { pre = pre || ' &a ...

A guide on transforming HTML into a variable using JavaScript

Having trouble converting HTML to a JavaScript variable. This is my HTML code: <div onclick="openfullanswer('2','Discription part','This is the code part');"> I want to create this HTML code dynamically, but I&apo ...

Jekyll is not beginning line numbers from the first line as they should be

My website was put together using Jekyll, specifically with the Beatiful-Jekyll theme. To make syntax highlighting possible, I utilized Rouge. The issue arises when displaying line numbers alongside the code - sometimes they don't align properly or ar ...

Having trouble making a simple pjax example function correctly

UPDATE: This example may not be functioning properly, check the link here: I am attempting to replicate a basic PJAX example as outlined in the readme (https://github.com/defunkt/jquery-pjax) Below is the content of index.html: <!DOCTYPE html> < ...

Trouble with incorporating numbers into Titanium

I have a query about adding a decimal number to a latitude value obtained using forwardGeocoder. Here's the code snippet I am referring to: Ti.Geolocation.forwardGeocoder(textField.value, function(e) { var a = e.latitude; var ...

The problem with legends in chart.js not displaying properly

I've been struggling to display the labels "2017" and "2018" as legends on the right side of the chart. I've tried numerous approaches but haven't found a solution yet. The purpose of showing these legends is to easily identify that each co ...

Utilize an array of JSON objects to populate an array of interfaces in Angular/Typescript

I am currently facing a dilemma - my code is functioning without any errors when executed, but my text editor is flagging an issue stating that the property 'categories' does not exist on type 'CategoryInterface[]' (specifically on the ...

How can dynamic values be displayed in VueJS?

I'm looking to display dynamic titles based on the number of times a value is added. For example, if a user selects cats and clicks Add, I want the title to show as cats 1. If the user adds it again, then it should be displayed as cats 2, and so on fo ...

Embarking on a New Project with Cutting-Edge Technologies: Angular, Node.js/Express, Webpack, and Types

Recently, I've been following tutorials by Maximilian on Udemy for guidance. However, I have encountered a roadblock while trying to set up a new project from scratch involving a Node/Express and Angular 4 application. The issue seems to stem from the ...

Troubleshooting Problem with Uploading Multiple Files to Server Using PHP, MySQL, and

Recently, I completed building a simple website for uploading files to the server and storing their names in a database for search functionality. The site was created following a tutorial available at www.formget.com. However, I encountered an issue when ...

Preventing scrollbar-induced content shifting in Material-UI components: A guide

My browser app displays content dynamically, which can vary in length compared to the screen size. This causes a vertical scrollbar to appear and disappear on desktop browsers, leading to the content shifting left and right. To prevent this, I apply style ...

JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below: function onlyDecimal(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) ...

Tips for utilizing document.write() with a document rather than just plain text

Currently, I am utilizing socket.io to develop a party game that shares similarities with cards against humanity. My main concern is how to retain the players' names and scores without needing to transmit all the data to a new page whenever new games ...

Optimizing express server dependencies for a smooth production environment

After developing an application with a React front end and a Node server on the backend, I found myself wondering how to ensure that all dependencies for the server are properly installed when deploying it on a container or a virtual machine. Running npm ...

Setting the default option in an Autocomplete component using Material UI in React JS

I am currently working with autocomplete input using react material ui component. One specific challenge I am facing is setting a default selected value when a user enters edit mode for this input field. Although I can select the option using getOptionSe ...

My JSON file is being populated with duplicate data when making an AJAX post call

I encountered an issue while working on my project. I am trying to create a news article archive using node.js. I capture all the necessary data from a form and store it in a JSON file. Here is a simplified version of my form: <form id="json-form&q ...

Calculating the total length of an SVG element using React

Looking to animate an SVG path using React (similar to how it's done in traditional JavaScript: https://css-tricks.com/svg-line-animation-works/), but struggling when the path is created using JSX. How can I find the total length of the path in this s ...

Populating dropdown menu with data from redux state upon component mounting

I am new to working with react-redux and have successfully implemented dependent dropdown functionality in a react component (Country => State => City). My goal now is to dynamically update the dropdown values based on data received from the redux s ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...