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.
If you are trying to convert the element to HTML, then you could give the
<ul>an ID then useOr, if there will be a lot of markup and you want to just get the text, you could loop through the
lielements and extract just the text and put that in an array.JSON.stringifythe result and get its length.Edit:
Javascript uses
UCS-2orUTF-16internally, both of which are 16 bit encodings. Assuming Latin text,<string>.length *2should be a fairly accurate estimate.