2

How to get the size of an HTML element in bytes using javascript?

I have a list that represents a conversation

<ul>
  <li>hello</li>
  <li>how are you?</li>
  <li>fine thanks</li>
  <li>nice to meet you</li>
  <li>nice to mmet you too</li>
</ul>

And I want to save that conversation to localStorage, but localStorage limit is 5MB in chrome, so I need to know the size in bytes for the list to do some validations.

1

1 Answer 1

4

If you are trying to convert the element to HTML, then you could give the <ul> an ID then use

var el = document.getElementById("convo");
var html = el.innerHTML;
window.alert(html.length);

Or, if there will be a lot of markup and you want to just get the text, you could loop through the li elements and extract just the text and put that in an array. JSON.stringify the result and get its length.

Edit:

Javascript uses UCS-2 or UTF-16 internally, both of which are 16 bit encodings. Assuming Latin text, <string>.length *2 should be a fairly accurate estimate.

Sign up to request clarification or add additional context in comments.

5 Comments

Length alone might not be enough to accurately get the number of bytes since it depends on the encoding aswell.
@Mahn -- Given that Javascript uses UCS-2 or UTF-16 internally, I'd work off the [unfounded, but good guess] that .localStorage uses the same encoding. While it may be a few bytes off, <string>.length *2 is a good estimate.
True, you didn't consider the 16 bits per char on your original answer though, hence the comment :)
For the record, here's more on the js specifications of string encoding (which is indeed UTF-16): stackoverflow.com/a/2219545/1329367 and here it talks about how localStorage uses UTF-16 strings aswell: stackoverflow.com/a/7411549/1329367 feel free to add these links to the answer for completeness sake.
@Mahn -- Its a little more complex than that. It uses a 16BIT word, but it doesn't have to be UTF-16: Read here - stackoverflow.com/questions/8715980/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.