I'm trying to set the less-than symbol and the less-than or equal symbol using innerHTML
, then get the encoded text back out, not the decoded symbols.
This works with <
, but not with ≤
. Is there a reason why this would be?
var lt = '<';
var le = '≤';
var div_lt = document.createElement('div');
div_lt.setAttribute('original_value', lt);
div_lt.innerHTML = lt;
var div_le = document.createElement('div');
div_le.setAttribute('original_value', le);
div_le.innerHTML = le;
console.log([div_lt.innerHTML, div_lt.innerText, div_lt.getAttribute('original_value')]);
// gives [ "<", "<", "<" ], as I expected
console.log([div_le.innerHTML, div_le.innerText, div_le.getAttribute('original_value')]);
// gives [ "≤", "≤", "≤" ], but the first value should be "≤"
JSFiddle: https://jsfiddle.net/54m6c8sk/
In HTML <
means "Start of tag" and ≤
means "≤".
When you want to express <
in HTML then you often must use an entity. When you want to express ≤
, you never have to use an entity.
Converting DOM to HTML via innerHTML
doesn't convert ≤
to ≤
because it is never useful to do so.
This is a fun one... but already answered: How do I prevent HTML encoding of '&' characters while copying content from a div to the title of the page?
tldr: use textContent instead of innerHTML -- innerHTML is actually not part of the DOM spec
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.