Show html as text javascript

JavaScript innerHTML, innerText, and textContent

In Javascript, there are three properties that can be used to set or return an HTML element’s content in the DOM: innerHTML, innerText, and textContent. If you are unsure about the differences and wondering which one to use, hopefully the following comparison will help. (1) The innerHTML property sets and returns the content of an element with new HTML content.

// Setting text with innerHTML: const example = document.getElementById('example') example.innerHTML = "

This is my paragraph.

"

Although HTML5 prevents a

// HTML5 prevents malicious " el.innerHTML = example1 const example2 = document.getElementById('example2') example2.innerHTML = '' // Examples of cybercriminals embedding Javascript without 

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Example

My First Web Page

My First Paragraph

document.getElementById("demo").innerHTML = 5 + 6;

Changing the innerHTML property of an HTML element is a common way to display data in HTML.

Using document.write()

For testing purposes, it is convenient to use document.write() :

Example

My First Web Page

My first paragraph.

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Example

My First Web Page

My first paragraph.

The document.write() method should only be used for testing.

Using window.alert()

You can use an alert box to display data:

Example

My First Web Page

My first paragraph.

You can skip the window keyword.

In JavaScript, the window object is the global scope object. This means that variables, properties, and methods by default belong to the window object. This also means that specifying the window keyword is optional:

Example

My First Web Page

My first paragraph.

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

You will learn more about debugging in a later chapter.

Example

JavaScript Print

JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to print the content of the current window.

Example

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

.inner H T M L

Свойство inner H T M L позволяет считать содержимое элемента в виде HTML-строки или установить новый HTML.

Новое значение HTML необходимо передавать в виде строки и оно заменит текущее содержимое элемента. При передаче невалидной HTML-строки будет выброшена ошибка. HTML-строкой является строка, которая содержит валидную HTML-разметку, в inner H T M L нельзя передать DOM-элемент.

Пример

Скопировать ссылку "Пример" Скопировано

     
Введите логин
form> label>Логинlabel> input type="text" id="login" /> div class="error">Введите логинdiv> form>
 const form = document.querySelector('form') console.log(form.innerHTML)// '
Введите логин
'
// Меняем содержимое новым htmlform.innerHTML = '
Вход выполнен
'
const form = document.querySelector('form') console.log(form.innerHTML) // '
Введите логин
'
// Меняем содержимое новым html form.innerHTML = '
Вход выполнен
'
   
Вход выполнен
form> div class="success">Вход выполненdiv> form>

Как понять

Скопировать ссылку "Как понять" Скопировано

Браузер предоставляет разработчику возможность управлять содержимым на странице и менять его как угодно. inner H T M L – самый простой способ считать или изменить HTML-содержимое элемента. Это свойство использует строки, что даёт возможность легко менять и очищать содержимое элементов.

Когда в inner H T M L присваивается новое значение, все предыдущее содержимое удаляется и создаётся новое, что приводит к перерисовке страницы.

Как пишется

Скопировать ссылку "Как пишется" Скопировано

Обращение к свойству inner H T M L вернёт содержимое элемента в виде HTML-строки. Просмотреть или изменить содержимое можно у всех элементов, включая и . Присвоение нового значения к свойству очистит всё текущее содержимое и заменит его новым HTML.

 document.body.innerHTML = 'Hello Inner HTML!' document.body.innerHTML = 'Hello Inner HTML!'      

В результате в документ будет вставлен HTML:

 

Hello Inner HTML!

h1>Hello Inner HTML!h1>

Стоит помнить, что строка с HTML-разметкой это не DOM-элемент. inner H T M L работает только со строками, самостоятельно разбирает её содержимое и создаёт элементы.

 const divEl = document.createElement('div') // document.body.innerHTML = divEl const divEl = document.createElement('div') // document.body.innerHTML = divEl     

Так как в div El находится объект DOM-элемента, то при присвоении в inner H T M L он приведётся к строке, в результате в элемент вставится строка " [ object H T M L Div Element ] " .

 [object HTMLDivElement] body>[object HTMLDivElement]body>      

Если передать в inner H T M L строку с невалидным HTML, то будет выброшена ошибка. Однако большинство современных браузеров помогают разработчику, умеют самостоятельно дополнять разметку (например если забыли закрыть тег) и даже дают возможность для кастомных тегов. Потому встретить ошибку при передаче в inner H T M L невалидного HTML очень сложно.

Несмотря на то, что с помощью inner H T M L вставить любой HTML, есть некоторые ограничения, связанные с безопасностью веб-приложений.

Так же не рекомендуется использовать inner H T M L , если нужно просто изменить текст в элементе. Для этой задачи есть свойство inner Text или text Content .

 // Скрипт станет частью body, но не выполнитсяdocument.body.innerHTML = '' // После вставки в html картинка не загрузится и тогда сработает код из onerrordocument.body.innerHTML = ' ' // Скрипт станет частью body, но не выполнится document.body.innerHTML = '' // После вставки в html картинка не загрузится и тогда сработает код из onerror document.body.innerHTML = ' '      

Источник

Читайте также:  Python request basic authentication
Оцените статью