HTML
<!DOCTYPE html>
<html lang=»ru»>
<head>
<meta charset=»utf-8″>
<link rel=»stylesheet» href=»setting.css»>
<link rel=»stylesheet» href=»style.css»>
<title>FlashNews!</title>
</head>
<body class=»page light-theme»>
<header class=»page-header»>
<div class=»container»>
<a class=»header-link» href=»#»>На главную</a>
<button class=»theme-button» type=»button»>Изменить тему</button>
</div>
</header>
<main class=»inner-main»>
<div class=»container»>
<h1 class=»inner-heading»>Подпишитесь на нашу рассылку</h1>
<p class=»subscription-message»>Обещаем присылать вам новости не чаще одного раза в день, причём только самые интересные и важные.</p>
<form action=»https://echo.htmlacademy.ru/courses» method=»post» class=»subscription»>
<div class=»subscription-inner»>
<label class=»subscription-label» for=»subscription-email»>email</label>
<input type=»email» class=»subscription-email» placeholder=»keks@flashnews.ru» value=»» required id=»subscription-email»>
</div>
<button class=»button subscription-button» type=»submit»>Подписаться</button>
</form>
<section class=»news-list list-tiles-view»>
<h2 class=»news-list-heading»>Или почитайте ещё немного новостей</h2>
<article class=»new-block»>
<img src=»img/new-graph.jpg» alt=»Новая библиотека»>
<div class=»new-block-text»>
<h3>Новая библиотека для создания графиков</h3>
<p>Теперь вы можете создать дашборд за считанные секунды.</p>
<time datetime=»2019-10-16″>16 октября 2019</time>
</div>
</article>
<article class=»new-block»>
<img src=»img/new-robot.jpg» alt=»Что там у роботов?»>
<div class=»new-block-text»>
<h3>Что там у роботов?</h3>
<p>В робототехнике происходит много интересного, эта новость могла бы быть об этом, но нет.</p>
<time datetime=»2019-10-15″>15 октября 2019</time>
</div>
</article>
</section>
</div>
</main>
<footer class=»page-footer»>
<div class=»container»>
<p>© FlashNews!</p>
<a class=»footer-logo»>
<img src=»img/white-logo.svg» alt=»Логотип портала FlashNews!»>
</a>
</div>
</footer>
<script src=»script.js»></script>
</body>
</html>
- How to change an element’s text content
- How to change an element’s innerHTML
- The innerText property
- Which text property should you use
- Summary: Points to remember
How to change an element’s text content
Javascript provides us with the textContent
property that we can use to change the text inside an element.
element.textContent = "new_value";
When we change the value of the property, it will completely overwrite the previous value.
<html>
<body>
<h1>Heading 1</h1>
</body>
<script>
// change the text content in the heading
document.querySelector("h1").textContent = "H1";
</script>
</html>
This property will only return the text inside an element. Any HTML inside the element will be stripped before the text is returned.
<html>
<body>
<p>
In this paragraph we have some <strong>bolded text</strong>,
some <em>italicized text</em> and a <a href="#">link</a>.
</p>
<p></p>
</body>
<script>
const p1 = document.querySelectorAll("p")[0]; // top p
const p2 = document.querySelectorAll("p")[1]; // bottom p
// place the first paragraph's text
// into the second one as demonstration
p2.textContent = p1.textContent;
</script>
</html>
If we run the example above, we can see the formatting that’s present in the top paragraph is no longer there in the bottom paragraph.
This means we cannot use textContent
to replace text with something that includes html.
<html>
<body>
<h1>Heading 1</h1>
</body>
<script>
// change the text content in the heading
document.querySelector("h1").textContent = '<a href="#">Link</a>';
</script>
</html>
If we run the example above, it will print the HTML code instead of creating a link.
How to change an element’s innerHTML
Javascript also provides us with the innerHTML
property that we can use to change the text inside an element.
<html>
<body>
<h1>Heading 1</h1>
</body>
<script>
// change the text content in the heading
document.querySelector("h1").innerHTML = "H1";
</script>
</html>
Unlike the textContent property, innerHTML
will return everything exactly as it is inside the element, including HTML.
<html>
<body>
<p>
In this paragraph we have some <strong>bolded text</strong>,
some <em>italicized text</em> and a <a href="#">link</a>.
</p>
<p></p>
</body>
<script>
const p1 = document.querySelectorAll("p")[0]; // top p
const p2 = document.querySelectorAll("p")[1]; // bottom p
// place the first paragraph's text
// into the second one as demonstration
p2.innerHTML = p1.innerHTML;
</script>
</html>
This time the second paragraph has all its formatting and the link is still available because innerHTML
brings any HTML along.
This means that we can include HTML elements when replacing text.
<html>
<body>
<h1>Heading 1</h1>
</body>
<script>
// change the text content in the heading
document.querySelector("h1").innerHTML = '<a href="#">Link</a>';
</script>
</html>
In the example above, the link is generated instead of displaying the code.
The innerText property
The innerText
property works the same as the textContent
property but will not return any hidden elements.
<html>
<body>
<p>
This paragraph has a <span style="display:none">hidden span element</span>
and a <span>visible span element</span>
</p>
<p></p>
<p></p>
</body>
<script>
const p = document.querySelectorAll("p");
// textContent will display the hidden element
p[1].textContent = "textContent: " + p[0].textContent;
// innerText will not
p[2].innerText = "innerText: " + p[0].innerText;
</script>
</html>
If we run the example above, we can see that innerText
doesn’t display the hidden element.
Both innerText
and textContent
will display content inside <script>
or <style>
tags.
<html>
<body>
<p></p>
<p></p>
</body>
<script>
const p = document.querySelectorAll("p");
const s = document.querySelector("script");
// textContent will display it on a single line
p[0].textContent = "textContent: " + s.textContent;
// innerText will keep the formatting
p[1].innerText = "innerText: " + s.innerText;
</script>
</html>
<html>
<style>
p {
color: #303030
}
</style>
<body>
<p></p>
<p></p>
</body>
<script>
const p = document.querySelectorAll("p");
const s = document.querySelector("style");
// textContent will display it on a single line
p[0].textContent = "textContent: " + s.textContent;
// innerText will keep the formatting
p[1].innerText = "innerText: " + s.innerText;
</script>
</html>
The only difference is that innerText
will keep the formatting, whereas textContent
will not.
Which text property should you use
It depends on your situation. If you simply want to change the text in an element, any of these properties will work.
- If you want to return or change the HTML inside an element, use innerHTML.
- If you want to return or change just the text inside an element, use innerText.
- If you want to return or change just the text inside hidden elements, use textContent.
Summary: Points to remember
- We can use the innerHTML, innerText and textContent properties to return or change text inside an element.
- The textContent property will return all text, including anything inside a hidden element.
- The innerText property will return all text, excluding anything inside a hidden element.
- The innerHTML property will return both text and any other HTML content inside the element.
HTML DOM позволяет JavaScript изменять содержимое элементов HTML.
Изменение выходного потока HTML
JavaScript может создавать динамическое HTML-содержимое:
Дата:
В JavaScript документ. Write () можно использовать для записи непосредственно в выходной поток HTML:
Пример
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Не используйте Document. Write () после загрузки документа. Он будет перезаписывать документ.
Изменение HTML-содержимого
Самый простой способ изменить содержимое элемента HTML с помощью свойства InnerHtml .
Чтобы изменить содержимое элемента HTML, используйте следующий синтаксис:
document.getElementById(id).innerHTML = new HTML
В этом примере изменяется содержимое элемента <p>:
Пример
<html>
<body>
<p id=»p1″>Hello World!</p>
<script>
document.getElementById(«p1»).innerHTML = «New text!»;
</script>
</body>
</html>
Пример объяснил:
- HTML-документ выше содержит элемент <p> с идентификатором = «P1»
- Мы используем HTML DOM для получения элемента с идентификатором = «P1»
- JavaScript изменяет содержимое (InnerHtml) этого элемента на «новый текст!»
В этом примере изменяется содержимое элемента <H1>:
Пример
<!DOCTYPE html>
<html>
<body>
<h1 id=»id01″>Old Heading</h1>
<script>
var element = document.getElementById(«id01»);
element.innerHTML = «New Heading»;
</script>
</body>
</html>
Пример объяснил:
- HTML-документ выше содержит элемент <H1> с идентификатором = «ид01»
- Мы используем HTML DOM, чтобы получить элемент с ID = «ид01»
- JavaScript изменяет содержимое (InnerHtml) этого элемента на «новый заголовок»
Изменение значения атрибута
Чтобы изменить значение атрибута HTML, используйте следующий синтаксис:
document.getElementById(id).attribute = new value
В этом примере изменяется значение атрибута src элемента <img>:
Пример
<!DOCTYPE html>
<html>
<body>
<img id=»myImage» src=»smiley.gif»>
<script>
document.getElementById(«myImage»).src = «landscape.jpg»;
</script>
</body>
</html>
Пример:
- HTML-документ выше содержит элемент <img> с идентификатором = «MYIMAGE»
- Мы используем HTML DOM, чтобы получить элемент с ID = «MYIMAGE»
- JavaScript изменяет атрибут src этого элемента из «Smiley. gif» на «альбомная. jpg»
PHPCSSJSHMTL Editor
Здравствуйте. Нужно реализовать так, чтобы в блоке div можно было динамически изменять текст. Например, пользователю задают вопрос, и он в этом же div пишет текст, и он заменяет старый. Нашел подобный готовый код, но нужно сделать не таблицей, а вывести либо отдельную форму для ввода текста либо в этом же div писать новый текст.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JS Change tag inner Text</title>
<style>
#text {
border: 1px solid rgb(117, 117, 117);
padding: 5px;
}
</style>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<table class="w3-table w3-table-all">
<tr>
<th>Модель</th>
<th>Стоимость</th>
</tr>
<tr>
<td class="editable" data-name="model-1-name">Samsung Galaxy S10</td>
<td class="editable" data-name="model-1-price">$1000.00</td>
</tr>
<tr>
<td class="editable" data-name="model-2-name">Apple 7 plus</td>
<td class="editable" data-name="model-2-price">$980.50</td>
</tr>
<tr>
<td class="editable" data-name="model-3-name">Huawei P20 Pro</td>
<td class="editable" data-name="model-3-price">$750.99</td>
</tr>
</table>
<p><button class="w3-button w3-round w3-yellow" onclick="document.querySelector('#new-field-popup').style.display='block'">+ Add field</button></p>
<script src="app.js"></script>
</body>
</html>
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);
});
Так же на codepen ссылка
Есть идеи, как это можно сделать?