JS Change tag inner Text

Element.innerHTML

Свойство интерфейса Element innerHTML устанавливает или получает HTML или XML разметку дочерних элементов.

Примечание: Если узлы , , или (en-US) имеют дочерние текстовые узлы, содержащие символы (&), (<), или (>) , innerHTML вернёт эти символы как &amp, &lt и &gt соответственно. Используйте Node.textContent для получения правильной копии содержимого этих текстовых узлов.

Чтобы вставить HTML в документ, не меняя содержимое элемента, используйте insertAdjacentHTML() .

Синтаксис

const content = element.innerHTML; element.innerHTML = htmlString; 

Значение

Строка DOMString , которая содержит части HTML разметки. Установка значения innerHTML удаляет всё содержимое элемента и заменяет его на узлы, которые были разобраны как HTML, указанными в строке htmlString.

Исключения

Возникает при попытке установить значение innerHTML строкой, в которой содержится неправильно сформированный HTML.

Возникает при попытке вставить HTML в узел, у которого родителем является Document .

Примечания

Это свойство предоставляет простой способ полностью заменить содержимое элемента. Например, все содержимое элемента body может быть удалено:

.body.innerHTML = ""; // Заменяет содержимое тела пустой строкой. 
// Скопируйте и вставьте в адресную строку в виде одной строки. javascript:"
"+document.documentElement.innerHTML.replace(//g,"<") + "

";

Это свойство было первоначально реализовано веб браузерами, затем описано WHATWG и W3C в HTML5. Старые реализации могут отличаться от новых. Для примера, когда введён текст в поле ввода , IE меняет значение атрибута свойства innerHTML, но браузеры Gecko не делают этого.

Соображения безопасности

Не редко можно увидеть использование InnerHTML для вставки текста в веб страницу. Это приводит к рискам безопасности.

const name = "John"; // предполагая, что 'el' является HTML DOM-элементом. el.innerHTML = name; // безвредный в этом случае // . name = ""; el.innerHTML = name; // безвредный в этом случае 

Хотя это может выглядеть как XSS-атака, результат безопасный. HTML5 указывает на тег вставленный через InnerHTM должен не выполнится.

const name = ""; el.innerHTML = name; // показывает alert 

По этой причине, рекомендуется не использовать innerHTML при вставке обычного текста; вместо этого, используйте node.textContent . Это не интерпретирует отправленный контент как HTML, но вместо этого он вставляется как не обработанный текст.

Пример

Этот пример использует innerHTML для создания механизма логирования сообщений внутри элемента на странице.

JavaScript

function log(msg)  var logElem = document.querySelector(".log"); var time = new Date(); var timeStr = time.toLocaleTimeString(); logElem.innerHTML += timeStr + ": " + msg + "
"
; > log("Регистрация событий мыши внутри этого контейнера. ");

Функция log() создаёт сообщение получая текущее время из объекта Date , используя toLocaleTimeString() , и соединяя строку с временной меткой с текстовым сообщением. Затем сообщение добавляется в элемент с классом «log» .

function logEvent(event)  var msg = "Event " + event.type + " at " + event.clientX + ", " + event.clientY + ""; log(msg); > 

Затем мы используем этот обработчик событий на элементе, который содержит наше логирование, для каждого события мыши:

var boxElem = document.querySelector(".box"); boxElem.addEventListener("mousedown", logEvent); boxElem.addEventListener("mouseup", logEvent); boxElem.addEventListener("click", logEvent); boxElem.addEventListener("mouseenter", logEvent); boxElem.addEventListener("mouseleave", logEvent); 

HTML

HTML довольно простой для нашего примера.

div class="box"> div>strong>Log:strong>div> div class="log">div> div> 

CSS

Для нашего примера используем следующие CSS стили.

.box  width: 600px; height: 300px; border: 1px solid black; padding: 2px 4px; overflow-y: scroll; overflow-x: auto; > .log  margin-top: 8px; font-family: monospace; > 

Результат

В результате мы получаем такое содержимое. Вы можете видеть логи наводя мышь на элемент, кликая на него и так далее.

Спецификации

Смотрите также

  • innerDOM — Для тех, кто хочет придерживаться стандартов, вот один набор функций JavaScript, предлагающий сериализовать или разобрать XML так, чтобы установить содержимое элемента, определённое как строка(и) через DOM или получить содержимое элемента, полученное из DOM как строку.
  • Element.insertAdjacentHTML — Альтернатива для innerHTML, позволяющая добавлять новый HTML.
  • jssaxparser — Более надёжным (хотя и более тяжёлым) решением, чем innerDOM (поддерживает парсинг с пространствами имён, однокавычками атрибутов, секциями CDATA и т.д.), является этот SAX2 парсер при использовании с его обработчиком DOM-контента. (Предлагает строку на DOM; DOM на строку значительно проще).
  • Эффективность соображений: quirksmode.

Found a content problem with this page?

This page was last modified on 14 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Как изменять текст в блоке div через Javascript?

Здравствуйте. Нужно реализовать так, чтобы в блоке div можно было динамически изменять текст. Например, пользователю задают вопрос, и он в этом же div пишет текст, и он заменяет старый. Нашел подобный готовый код, но нужно сделать не таблицей, а вывести либо отдельную форму для ввода текста либо в этом же div писать новый текст.

       #text   
Модель Стоимость
Samsung Galaxy S10 $1000.00
Apple 7 plus $980.50
Huawei P20 Pro $750.99

function TagContentChanger(selector,onBlurCallback) < let elements = document.querySelectorAll(selector); function process(element,callback) < let bg = element.style.background; element.addEventListener('click', (event) =>< element.setAttribute('contenteditable',true); element.style.background = "rgb(113, 179, 240)"; >); element.addEventListener('blur', (event) => < if( element.hasAttribute('contenteditable') ) < element.removeAttribute('contenteditable',false); element.style.background = bg; callback(element); >>); > for(let element of elements) < process(element,onBlurCallback); >> function fillEditables(selector) < let elements = document.querySelectorAll(selector); for(let element of elements) < let value = localStorage.getItem(element.dataset.name); if( !value ) return; else element.innerText = value.trim(); >> fillEditables('.editable'); TagContentChanger('.editable', (element) => < localStorage.setItem(element.dataset.name,element.innerText); >);

Есть идеи, как это можно сделать?

Источник

Javascript заменить содержимое div

Last updated: Jan 12, 2023
Reading time · 2 min

banner

# Change the Text of an Element in JavaScript

Use the textContent property to change the text of an element.

The textContent property will set the text of the element to the provided string, replacing any of the existing content.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="container">Initial Textdiv> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const div = document.getElementById('container'); // ✅ Change (replace) the text of the element div.textContent = 'Replacement text'; // ✅ Change (replace) the content with HTML div.innerHTML = `span style="background-color: lime">Replacement HTMLspan>`; // ✅ Append / Prepend text to the element div.insertAdjacentText('beforeend', ' appended text'); // ✅ Append / Prepend HTML to the element div.insertAdjacentHTML( 'beforeend', ` appended HTML`, );

change text of div element

We used the textContent property on the div to change its text content.

The textContent property can also be used to read the text content of an element and its descendants.

Setting textContent on an element removes all of the element’s children and replaces them with a single text node with the provided string.

If you need to completely replace the HTML content of the div , use the innerHTML property.

Copied!
const div = document.getElementById('container'); // ✅ Change (replace) the text with HTML div.innerHTML = `span style="background-color: lime">Replacement HTMLspan>`;

The innerHTML property gets or sets the HTML contained within the element.

By setting the property on the element, you effectively replace the previously contained HTML in the div .

You shouldn’t use user-generated data without escaping it when setting the HTML of an element because it would leave your application vulnerable to XSS attacks.

If you need to append/prepend text to the existing content of the div element, use the insertAdjacentText method instead.

Copied!
const div = document.getElementById('container'); // ✅ Append / Prepend text to the element div.insertAdjacentText('beforeend', ' appended text');

The insertAdjacentText method takes the following 2 parameters:

  1. position — the position relative to the element where the text should be inserted. Can be one of the following 4:
  • beforebegin — before the element itself.
  • afterbegin — just inside the element, before its first child.
  • beforeend — just inside the element, after its last child.
  • afterend — after the element itself.
  1. data — the string from which to create a new text node to insert at the given position.

We inserted text just inside the div element, before its last child, but you can change the value of the position parameter depending on your use case.

If you need to insert HTML into the div , use the insertAdjacentHTML method.

Copied!
const div = document.getElementById('container'); // ✅ Append / Prepend HTML to the element div.insertAdjacentHTML( 'beforeend', ` appended HTML`, );

The first parameter the insertAdjacentHTML method takes is the same as insertAdjacentText — the position at which the HTML should be inserted.

The second parameter is an HTML string containing the content you want to insert.

Note that this method shouldn’t be used with user-provided data without it being escaped, as it would leave you open to cross-site scripting attacks.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Отличие reader от inputstream java
Оцените статью