What is outer html

What is outerHTML in JavaScript?

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

The outerHTML property is used to set and get the HTML content of the element and its children.

Syntax

Get HTML Content

let htmlString = element.outerHTML; 

Set HTML content

element.outerHTML = htmlString; 

When we set the outerHTML of an element, the element and all the child nodes of the element are replaced with the passed HTML String The passed HTML String is parsed internally. .

Example

  • We access the outerHTML property of the div element to get the HTML of the div and its children.
  • When we set the outerHTML of an element, the element and its children are replaced with the passed HTML String.

Points to be noted

If we set outerHTML to an element that has no parent element e.g., elements that are not appended to the DOM , DOMException will be thrown.

 var p = document.createElement("p"); p.outerHTML = " 

not replaced

"; console.log(p.outerHTML); // DOMException

When we get the HTML content through the outerHTML property, if the HTML String contains & , < , >characters, then it will be replaced by the & , < , > entities, respectively.

Читайте также:  Background color css firefox

Imagine that we have a variable reference for an element. We replace the HTML content of the element using outerHTML property. In this case, the variable still points to the replaced element.

var divEle = document.getElementById("content"); console.log(divEle); divEle.outerHTML = "
This div replaced a paragraph.
"; console.log(divEle); // even the div element is replaced. The divEle variable still have reference to the replaced element.

Источник

.outer H T M L

Читаем и заменяем HTML-элемент и всё его содержание на новое.

Время чтения: меньше 5 мин

Кратко

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

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

Новое значение HTML передаётся в виде строки и оно полностью заменит весь элемент. В outer H T M L нельзя передать DOM-элемент, только строку.

Пример

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

   

Введение

Параграф с текстом

Второй параграф с текстом

section> h1>Введениеh1> p>Параграф с текстомp> p>Второй параграф с текстомp> section>
 const section = document.querySelector('section') console.log(section.outerHTML) const section = document.querySelector('section') console.log(section.outerHTML)      

В таком случае выведется весь HTML, включая сам элемент:

 

Введение

Параграф с текстом

Второй параграф с текстом

section>h1>Введениеh1>p>Параграф с текстомp>p>Второй параграф с текстомp>section>

Если теперь заменить содержимое новым HTML

 section.outerHTML = '

Второй заголовок

'
section.outerHTML = '

Второй заголовок

'

HTML после изменения будет:

 

Второй заголовок

h2>Второй заголовокh2>

Как понять

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

Свойство outer H T M L проще понять в сравнении с другим похожим свойством – inner H T M L .

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

Так же как и inner H T M L , если в outer H T M L присвоить новое значение, то это приводит к перерисовке страницы.

Как пишется

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

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

Присвоение нового значения к свойству полностью удалит элемент и заменит его новым HTML:

 
Название сайта
header>Название сайтаheader>
 const header = document.querySelector('header') header.outerHTML = ' ' const header = document.querySelector('header') header.outerHTML = ' '      

HTML после изменения будет:

 span class="logo">span>      

Новый элемент полностью заменит .

 document.body.outerHTML = 'Я новое содержимое страницы' document.body.outerHTML = 'Я новое содержимое страницы'      

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

   Я новое содержимое страницы  body> h1>Я новое содержимое страницыh1> body>      

остался на странице, а новое значение стало содержимым элемента.

Если попробовать изменить outer H T M L у , то браузер выбросит ошибку.

 const html = document.querySelector('html') html.outerHTML = '
Я новый HTML
'
// Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element'
const html = document.querySelector('html') html.outerHTML = '
Я новый HTML
'
// Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element'

Источник

Element.outerHTML

Атрибут outerHTML DOM-интерфейса element получает сериализованный HTML-фрагмент, описывающий элемент, включая его потомков. Можно установить замену элемента узлами, полученными из заданной строки.

Синтаксис

var content = element.outerHTML;

На выводе, content содержит сериализованный HTML-фрагмент, описывающий element и его потомки.

element.outerHTML = content;

Replaces the element with the nodes generated by parsing the string content with the parent of element as the context node for the fragment parsing algorithm.

Примеры

Получение свойства outerHTML элемента:

// HTML: // 

Content

Further Elaborated

d = document.getElementById("d"); console.log(d.outerHTML); // строка '

Content

Further Elaborated

'
// выведена в окно консоли

Замена ветки с помощью изменения свойства outerHTML :

// HTML: // 
Это div.
container = document.getElementById("container"); d = document.getElementById("d"); console.log(container.firstChild.nodeName); // логирует "DIV" d.outerHTML = "

Этот параграф заменил исходный div.

"
; console.log(container.firstChild.nodeName); // логирует "P" // div #d больше не часть дерева документа, // новый параграф заменил его.

Примечания

Если у элемента нет родительской ветки, которая не является корневой веткой документа, установка его свойства outerHTML выбросит исключение DOMException с кодом ошибки NO_MODIFICATION_ALLOWED_ERR . Например:

.documentElement.outerHTML = "test"; // бросает DOMException 

Обратите внимание, когда произойдёт изменение элемента в документе, переменная, у которой было установлено свойство outerHTML , будет по-прежнему хранить ссылку на оригинальный элемент:

var p = document.getElementsByTagName("p")[0]; console.log(p.nodeName); // показывает: "P" p.outerHTML = "
Этот div заменил параграф.
"
; console.log(p.nodeName); // всё ещё "P";

Specification

Поддержка браузерами

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on 19 окт. 2022 г. 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.

Источник

Alert the outer HTML of a element:

The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.

Syntax

Return the outerHTML property:

Set the outerHTML property:

Property Value

Return Value

Browser Support

element.outerHTML is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

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.

Источник

The Difference Between Inner and Outer HTML

These two properties are quite descriptive, once you understand their context.

A file icon containing the word “JS” alongside a semi-colon inside curly brackets

Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

The innerHTML and outerHTML DOM properties allow you to read and write content on a webpage. You can use them to fetch markup or make changes to it, and the two are similar in many ways. But there is a significant difference.

When working with the DOM, you’ll use innerHTML and outerHTML quite differently. Find out how to use these two properties with practical examples.

What Is Inner HTML?

The innerHTML property is part of the DOM and you can access it via JavaScript. You can use it to get or set the contents of an element. This content excludes the element’s own tag and only includes the markup that represents the element’s children, in the form of a string.

Consider this code sample:

html>

body>
p id=«myP»>I am a paragraph. p>

script>
document.getElementById(«myP»).innerHTML = «Hello World»;
script>
body>

html>

In your browser, you’ll see a standard paragraph with the replacement text, like so:

inner HTML changes paragraph contents

The innerHTML property selects and changes the contents of the element in this example.

What Is Outer HTML?

The outerHTML property is like innerHTML in many ways. You can use it to get or set the contents of a selected element. However, it also sets the markup representing the element itself. This includes the opening tag, any properties, and—where relevant—the closing tag.

Revisit the previous example to see how outerHTML differs:

html>

body>
p id="myP">I am a paragraph. p>

script>
document.getElementById("myP").outerHTML = "

This H1 replaced a paragraph.

"

script>
body>

html>

In your browser, you should see something like this:

outerHTML replaces HTML content and tag

In this example, the outerHTML property changes the p element into an h1 element.

Know the Difference and When to Use These Properties

The innerHTML and outerHTML DOM properties have many similarities, but one key difference. The innerHTML property captures the HTML contents of an element. In contrast, the outerHTML property captures the HTML that represents the element itself and its content.

You can use these properties to read and write HTML content via the DOM. The DOM will be a common, important concept throughout your JavaScript development process.

Источник

Оцените статью