JavaScript Answers jQuery

How to Determine the Pixel Length of a String in JavaScript and jQuery?

Spread the love

To determine the pixel length of a string in JavaScript and jQuery, we can put the string in a span and then use the jQuery width method to determine the width of the span.

For instance, we can write the following HTML:


Then we can write:

const span = document.querySelector('span')  
span.innerText = 'Here is my string'  

to get the span width document.querySelector .

And then we set innerText to the string of the span.

Finally, we log the span’s width that we get from $(span).width() from jQuery.

The console log should log 111.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *