Daniel Williams Daniel Williams - 7 months ago 8
Javascript Question

Getting the width of html content inside an LI that's 100% wide

In my snippet, my OL has a CSS width of 100%. In my jQuery I want to get the width (like offsetWidth in vanilla JS) of the content inside the LI tag, but the jQuery

width()
returns the width of the LI, which ends up being the full width of the browser (instead of around 140 pixels).



$(document).ready(function(){

alert($("#theOl li:eq(0)").width());
});

#theOl {
border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ol id="theOl">
<li>This is some text
</ol>





Note, that I need the LI itself to remain at 100% width.

Answer

Why not wrap the <li> content in a span, and simply get the width of that?

$(document).ready(function(){
    
    alert($("#theOl li:eq(0) span").width());
});
#theOl {
  border: 1px solid red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ol id="theOl">
  <li><span>This is some text</span>
</ol>

Comments