В примере документации, показанном на MDN , они говорят:
Этот пример сравнивает innerText
с Node.textContent
. Обратите внимание, что innerText
знает о таких вещах, как теги <br>
, и игнорирует скрытые элементы.
Теперь я проверил это на Firefox 66.0.3 (64bits)
, и оно все еще работает, если элемент, из которого / где вы устанавливаете / получаете свойства, отображается или существует на document.body
во время выполнения операций, вы можете проверить следующие два примеры:
Пример 1:
const textToHtml = (text) => {
const div = document.getElementById('test');
div.innerText = text;
return div.innerHTML;
}
const htmlToText = (html) => {
const div = document.getElementById("test");
div.innerHTML = html;
console.log("Note <br> is parsed to \\n ->", div.innerText);
return div.innerText;
}
console.log("Output ->", textToHtml(htmlToText(`Some<br>Other`)));
.as-console {background-color:black !important; color:lime;}
<div id="test"></div>
Пример 2:
const textToHtml = (text) => {
const div = document.createElement('div');
document.body.append(div);
div.innerText = text;
return div.innerHTML;
}
const htmlToText = (html) => {
const div = document.createElement('div');
document.body.append(div);
div.innerHTML = html;
console.log("Note <br> is parsed to \\n ->", div.innerText);
return div.innerText;
}
console.log("Output ->", textToHtml(htmlToText(`Some<br>Other`)));
.as-console {background-color:black !important; color:lime;}
И, как вы говорите, он не будет работать (в некоторых новых браузерах), если элемент не существует в document
, однако я точно не знаю, в чем причина (возможно, это так). потому что созданный вами элемент не отображается):
const textToHtml = (text) => {
const div = document.createElement('div');
div.innerText = text;
return div.innerHTML;
}
const htmlToText = (html) => {
const div = document.createElement('div');
div.innerHTML = html;
console.log("Note <br> isn't parsed to \\n ->", div.innerText);
return div.innerText;
}
console.log("Output ->", textToHtml(htmlToText(`Some<br>Other`)));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
В любом случае, я пришел к следующему подходу, который создает элементы, добавляет их к body
, а затем removes
, чтобы у вас не было визуального возмущения:
Новая реализация:
const textToHtml = (text) => {
const div = document.createElement('div');
document.body.append(div);
div.innerText = text;
const html = div.innerHTML;
div.remove();
return html;
}
const htmlToText = (html) => {
const div = document.createElement('div');
document.body.append(div);
div.innerHTML = html;
const text = div.innerText;
div.remove();
return text;
}
console.log("Output ->", textToHtml(htmlToText(`Some<br>Other`)));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Дополнительно: Есть хорошее прочтение о innerText
на the-бедный-неправильно-понимаемый-внутренний-текст