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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
Art Grc
  • 453
  • 2
  • 8
  • 14
  • http://stackoverflow.com/questions/3027142/calculating-usage-of-localstorage-space on Calculating usage of localStorage space – Mifeng Sep 18 '12 at 13:21

1 Answers1

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.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
  • Length alone might not be enough to accurately get the number of bytes since it depends on the encoding aswell. – Mahn Sep 18 '12 at 13:02
  • @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, `.length *2` is a good estimate. – Jeremy J Starcher Sep 18 '12 at 13:06
  • 1
    True, you didn't consider the 16 bits per char on your original answer though, hence the comment :) – Mahn Sep 18 '12 at 14:41
  • For the record, here's more on the js specifications of string encoding (which is indeed UTF-16): http://stackoverflow.com/a/2219545/1329367 and here it talks about how localStorage uses UTF-16 strings aswell: http://stackoverflow.com/a/7411549/1329367 feel free to add these links to the answer for completeness sake. – Mahn Sep 18 '12 at 14:58
  • @Mahn -- Its a little more complex than that. It uses a 16BIT word, but it doesn't have to be `UTF-16`: Read here - http://stackoverflow.com/questions/8715980/javascript-strings-utf-16-vs-ucs-2 – Jeremy J Starcher Sep 18 '12 at 15:21