- JavaScript | Как получить код HTML-страницы?
- Как объект document превратить в строку с HTML-разметкой?
- Одной командой
- Видео инструкция
- Задача
- Немножко теории
- Решение
- Итог
- Информационные ссылки
- Вам также может понравиться
- JavaScript | Как найти чётное число в строке?
- JavaScript | Как получить каждый второй элемент массива?
- JavaScript | Как получить символ по символьному коду?
- JavaScript | Что такое this?
- Element: innerHTML property
- Value
- Exceptions
- Usage notes
- Reading the HTML contents of an element
- Replacing the contents of an element
- Operational details
- Appending HTML to an element
- HTML
- JavaScript
- Security considerations
- Examples
- JavaScript
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to return HTML or build HTML using JavaScript?
- Returning HTML from a function
- Building HTML using DOM methods
- Example
- Building HML using DOM methods
- Building HTML using innerHTML
- Example
- Conclusion
JavaScript | Как получить код HTML-страницы?
Как объект document превратить в строку с HTML-разметкой?
Одной командой
new XMLSerializer().serializeToString(document)
Куда вводить эту команду? Открываете HTML-страницу, с которой хотите получить все веб-ссылки. Включаете «Инструменты разработчика» в браузере (CTRL + SHIFT + i). Находите вкладку «Console«. Тыкаете курсор в белое поле справа от синей стрелочки. Вставляете команду. Жмёте клавишу ENTER.
Для тех кто не понял строчку кода выше, предлагаю упрощённую для понимания версию. Пошаговая инструкция и видео ниже.
Видео инструкция
В этом видео приводится пример преобразования HTML-элемента в строку при помощи JavaScript. Ввод команд осуществляется в консоль браузера Google Chrome. Результат виден сразу.
Задача
У нас открыта вкладка в браузере. В этой вкладке отрисована HTML-страница, которая пришла с сервера.
Нам нужно получить код данной HTML-страницы — разметку. Мы хотим получить разметку в виде СТРОКИ. То есть нам как-то нужно преобразовать объект HTML-элемента в строковый тип данных JavaScript.
Немножко теории
«Объектная модель документа» (DOM) преобразовывает СТРОКУ кода c сервера в объект document . Этот объект хранит в себе наборы элементов и их последовательности. Самый правильный сценарий — это сделать GET-запрос на сервер и достать данные при помощи функции fetch(). Но нам нужно понять способ КОНВЕРТАЦИИ из уже готового объекта.
У объекта document есть готовый набор атрибутов, который помогает извлекать данные из страниц. Два атрибута, на которые можно акцентировать внимание — это documentElement и doctype. Но эти данные являются объектами, а не строками.
В данной задаче извлекать их по отдельности не имеет смысла. Просто вы должны понимать структуру объекта document . Внутри объекта тоже объекты, а не строки.
Решение
Нам нужно использовать интерфейс XMLSerializer, который имеет один единственный метод serializeToString(). Этот метод вернёт нам СТРОКУ из ОБЪЕКТА.
Сперва нам нужно создать новый конструктор сериализатора разметки:
Теперь мы можем вызвать метод serializeToString() и передать в него наш объект document .
a.serializeToString(document)
На выходе мы получаем СТРОКУ с HTML-разметкой. Тип данных STRING. Даже консоль браузера нам подсвечивает её красно-коричневым цветом.
typeof(new XMLSerializer().serializeToString(document)) "string"
Можно без объявления лишних переменных сразу получить строку с HTML-разметкой
new XMLSerializer().serializeToString(document)
Итог
Мы выполнили задачу и получили весь код HTML-страницы.
Информационные ссылки
Стандарт DOM Parsing and Serialization — https://www.w3.org/TR/DOM-Parsing/
Вам также может понравиться
JavaScript | Как найти чётное число в строке?
Есть строка: let stroka = ’23 cтроителя из бригады 15.0 залили 604,8 м бетона из необходимых 1042 м. Это -36 м от […]
JavaScript | Как получить каждый второй элемент массива?
Мы хотим получить из массива каждый второй элемент. Как это сделать? У нас есть массив: let massiv = [1,2,3,4,5,6,7,8,9,10]; Мы взяли массив […]
JavaScript | Как получить символ по символьному коду?
У нас есть символьный код 1067. Мы не знаем что это за символ, но хотим делать по нему проверку строк. Как […]
JavaScript | Что такое this?
Давай начнём издалека, чтобы ты точно смог понять что такое this в JavaScript. Ключевые зарезервированные слова в JavaScript Во-первых, this — […]
Element: innerHTML property
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .
Value
A string containing the HTML serialization of the element’s descendants. Setting the value of innerHTML removes all of the element’s descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.
Exceptions
Thrown if an attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.
Thrown if an attempt was made to insert the HTML into a node whose parent is a Document .
Usage notes
The innerHTML property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.
Reading the HTML contents of an element
Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element’s descendants. The resulting string is returned.
let contents = myElement.innerHTML;
This lets you look at the HTML markup of the element’s content nodes.
Note: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.
Replacing the contents of an element
Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.
Note: This is a security risk if the string to be inserted might contain potentially malicious content. When inserting user-supplied data you should always consider using Element.setHTML() instead, in order to sanitize the content before it is inserted.
For example, you can erase the entire contents of a document by clearing the contents of the document’s body attribute:
This example fetches the document’s current HTML markup and replaces the »
.documentElement.innerHTML = ` $document.documentElement.innerHTML.replace( //g, "<", )> `;
Operational details
What exactly happens when you set value of innerHTML ? Doing so causes the user agent to follow these steps:
- The specified value is parsed as HTML or XML (based on the document type), resulting in a DocumentFragment object representing the new set of DOM nodes for the new elements.
- If the element whose contents are being replaced is a element, then the element’s content attribute is replaced with the new DocumentFragment created in step 1.
- For all other elements, the element’s contents are replaced with the nodes in the new DocumentFragment .
Appending HTML to an element
Setting the value of innerHTML lets you append new contents to the existing one of an element.
HTML
ul id="list"> li>a href="#">Item 1a>li> li>a href="#">Item 2a>li> li>a href="#">Item 3a>li> ul>
JavaScript
Please note that using innerHTML to append HTML elements (e.g. el.innerHTML += «link» ) will result in the removal of any previously set event listeners. That is, after you append any HTML element that way you won’t be able to listen to the previously set event listeners.
Security considerations
It is not uncommon to see innerHTML used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.
let name = "John"; // assuming 'el' is an HTML DOM element el.innerHTML = name; // harmless in this case // … name = ""; el.innerHTML = name; // harmless in this case
Although this may look like a cross-site scripting attack, the result is harmless. HTML specifies that a tag inserted with innerHTML should not execute.
const name = ""; el.innerHTML = name; // shows the alert
For that reason, it is recommended that instead of innerHTML you use:
- Element.setHTML() to sanitize the text before it is inserted into the DOM.
- Node.textContent when inserting plain text, as this inserts it as raw text rather than parsing it as HTML.
Warning: If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it may be rejected in the review process. Please see Safely inserting external content into a page for alternative methods.
Examples
This example uses innerHTML to create a mechanism for logging messages into a box on a web page.
JavaScript
function log(msg) const logElem = document.querySelector(".log"); const time = new Date(); const timeStr = time.toLocaleTimeString(); logElem.innerHTML += `$timeStr>: $msg>
`; > log("Logging mouse events inside this container…");
The log() function creates the log output by getting the current time from a Date object using toLocaleTimeString() , and building a string with the timestamp and the message text. Then the message is appended to the box with the class «log» .
We add a second method that logs information about MouseEvent based events (such as mousedown , click , and mouseenter ):
function logEvent(event) const msg = `Event $event.type> at $event.clientX>, $event.clientY> `; log(msg); >
Then we use this as the event handler for a number of mouse events on the box that contains our log:
const 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
The HTML is quite simple for our example.
div class="box"> div>strong>Log:strong>div> div class="log">div> div>
CSS
The following CSS styles our example content.
.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; >
Result
The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Node.textContent and HTMLElement.innerText
- Element.insertAdjacentHTML()
- Element.outerHTML
- Element.setHTML
- Parsing HTML or XML into a DOM tree: DOMParser
- Serializing a DOM tree into an XML string: XMLSerializer
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How to return HTML or build HTML using JavaScript?
When building web applications, there are often times when you need to dynamically generate HTML on the client-side. This can be done using JavaScript, and there are different ways to go about it. In this article, we’ll show you how to return HTML or build HTML using JavaScript.
Returning HTML from a function
One way to dynamically generate HTML is to return a string of HTML from a function. For example, let’s say we have a function that generates a list item −
We can then use this function to generate HTML −
The list variable now contains the following HTML −
Building HTML using DOM methods
Another way to dynamically generate HTML is to use DOM methods to build the HTML structure. This can be done by creating elements and then adding them to the DOM. For example, let’s say we want to create a list with the same items as before −
var list = document.createElement('ul'); var item1 = document.createElement('li'); item1.innerText = 'Item 1'; list.appendChild(item1); var item2 = document.createElement('li'); item2.innerText = 'Item 2'; list.appendChild(item2); var item3 = document.createElement('li'); item3.innerText = 'Item 3'; list.appendChild(item3);
The list variable now contains the following HTML −
Example
In the example below, we build HTML list using different DOM methods.
Building HML using DOM methods
We create a list by generating HTML elementsvar list = document.createElement('ul'); var item1 = document.createElement('li'); item1.innerText = 'JavaScript'; list.appendChild(item1); var item2 = document.createElement('li'); item2.innerText = 'Python'; list.appendChild(item2); var item3 = document.createElement('li'); item3.innerText = 'Rupy'; list.appendChild(item3); document.getElementById("result").appendChild(list)In the above program, we used the createElement method to create an unordered list and list items. The appendChild method is used to add the list items to the list.
Building HTML using innerHTML
Another way to build HTML is to use the innerHTML property. This can be done by creating an element and then setting its innerHTML property to a string of HTML. For example, let’s say we want to create a list with the same items as before −
The list variable now contains the following HTML −
Example
In the example below, we build an HTML list by assigning the list to the innerHTML.
In the above program, we create a list using the createElement method. The list items are added to the list using the innerHTML. To display the list we appended the element with using appendChild method.
Conclusion
In this tutorial, we’ve shown how to return HTML or build HTML using JavaScript. There are different ways to go about it, and the method you choose will depend on your needs.