jQuery - why each can't get the width of hidden elements?

1.2k views Asked by At

Why each can't get the width of hidden elements?

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

But I thought it should be:

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

Any ideas? How can I get the width of these hidden elements?

EDIT:

I can get the width of the hidden element here:

<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

Why?

1

There are 1 answers

1
Win On BEST ANSWER

You can do something really hacky by cloning and turning visibility off. Once it's been inserted it into the DOM, we remove it after the width has been taken.

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>