Yetimwork Beyene
Yetimwork Beyene

Reputation: 2337

how to get the text width?

I have the following situation.

 <ul>
      <li><span> text </span></li>
 </ul>

I use the following jquery to get the text content and width...

  $("ul li").each(function()
  {
       var textIndex = $(this).index();
       var $text = $(this).find("span").text()  // this works..
       var textWidth = $text.width(); // this does not work..
  });

How do I get the text Width along with getting its index, and text data?

Upvotes: 0

Views: 9064

Answers (2)

arb
arb

Reputation: 7863

A few things:

  1. You can change your each function to include, index and value. Then you can get the index of the li without the extra jQuery call.
  2. The .text() call returns the text as a string, strings do not have a .width() method on them.
  3. I think what you really want is the width of the span, not the text.

Try this:

  $("ul li span").each(function(index,value)
  {
       var $value = $(value),
           textIndex = index,
           text = $value.text(),
           textWidth = $value.width();
  });

Upvotes: 2

BrunoLM
BrunoLM

Reputation: 100331

.text() returns a string (the text content of the element).

If by width you mean length (number of characters) then use

$text.length

To get the element width use

$("element-to-get-width-from").width()

And you want to get the index of what? From the LI inside an UL? Then use

$(this).index()

jQuery docs:

Upvotes: 1

Related Questions