Для привлечения внимания пользователя, например о каком либо событии, изменяют title страницы (особенно это заметно когда вкладка с сайтом не активна).
В JS за содержимое элемента <title>
отвечает свойство document.title
, оно содержит текущий заголовок документа:
var title = document.title;
console.log(title);
JS
А также назначает новый:
document.title = 'Новый заголовок страницы';
JS
Тitle в JQuery
В JQuery работа с тайтлом происходит как с обычном элементом:
var title = $('title').text();
console.log(title);
JS
$('title').text('Новый заголовок страницы');
JS
Далее несколько примеров как сделать динамический заголовок страницы.
1
Бегущая строка в title
<button id="start">Запустить</button>
<button id="stop">Остановить</button>
<script>
var timer;
var start_title = document.title;
$('#start').click(function(){
for (i = 0; i < 5; i++) {
document.title = document.title + ' | ' + start_title;
}
timer = setInterval(function(){
lenta = document.title;
if (lenta.length == 100){
lenta = lenta + ' | ' + start_title;
}
document.title = lenta.substr(1, lenta.length);
}, 100);
});
$('#stop').click(function(){
clearInterval(timer);
document.title = start_title;
});
</script>
HTML
Результат:
2
Мигающий заголовок страницы
Поочередный вывод сообщения «* Новое сообщение *» в <title>
:
<button id="start">Запустить</button>
<button id="stop">Остановить</button>
<script>
var timer;
var counter = 0;
var start_title = document.title;
var message = '* Новое сообщение *';
$('#start').click(function(){
timer = setInterval(function(){
if (counter % 2) {
document.title = start_title;
} else {
document.title = message;
}
counter++;
}, 1000);
});
$('#stop').click(function(){
clearInterval(timer);
document.title = start_title;
});
</script>
HTML
Результат:
There are many ways you can change the title, the main two, are like so:
The Questionable Method
Put a title tag in the HTML (e.g. <title>Hello</title>
), then in javascript:
let title_el = document.querySelector("title");
if(title_el)
title_el.innerHTML = "World";
The Obviously Correct Method
The simplest of all is to actually use the method provided by the Document Object Model (DOM)
document.title = "Hello World";
The former method is generally what you would do to alter tags found in the body of the document. Using this method to modify meta-data tags like those found in the head (like title
) is questionable practice at best, is not idiomatic, not very good style to begin with, and might not even be portable. One thing you can be sure of, though, is that it will annoy other developers if they see title.innerHTML = ...
in code they are maintaining.
What you want to go with is the latter method. This property is provided in the DOM Specification specifically for the purpose of, as the name suggests, changing the title.
Note also that if you are working with XUL, you may want to check that the document has loaded before attempting to set or get the title, as otherwise you are invoking undefined behavior
(here be dragons), which is a scary concept in its own right. This may or may not happen via JavaScript, as the docs on the DOM do not necessarily pertain to JavaScript. But XUL is a whole ‘nother beast, so I digress.
Speaking of .innerHTML
Some good advice to keep in mind would be that using .innerHTML
is generally sloppy. Use appendChild
instead.
Although two cases where I still find .innerHTML
to be useful include inserting plain text into a small element…
label.innerHTML = "Hello World";
// as opposed to...
label.appendChild(document.createTextNode("Hello World"));
// example:
el.appendChild(function(){
let el = document.createElement("span");
el.className = "label";
el.innerHTML = label_text;
return el;
}());
…and clearing out a container…
container.innerHTML = "";
// as opposed to... umm... okay, I guess I'm rolling my own
[...container.childNodes].forEach(function(child){
container.removeChild(child);
});
Improve Article
Save Article
Improve Article
Save Article
Given a web page containing the page title and the task is to change the title of a web page dynamically using JavaScript.
Method 1: Using JavaScript document.title property.
This property is used to set or return the current title of the document. The title of the page can be changed by assigning the new title as a string to this property. This will change the title of the website to the preferred title.
Syntax:
newPageTitle = 'The title has changed!'; document.title = newPageTitle;
Example:
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to dynamically change a web
page’s title using JavaScript ?
</
title
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>
GeeksforGeeks
</
h1
>
<
b
>
How to dynamically change a web
page’s title using JavaScript ?
</
b
>
<
p
>
Click on the button to change the page
title to: "The title has changed!"
</
p
>
<
button
onclick
=
"changePageTitle()"
>
Change Page Title
</
button
>
<
script
type
=
"text/javascript"
>
function changePageTitle() {
newPageTitle = 'The title has changed!';
document.title = newPageTitle;
}
</
script
>
</
body
>
</
html
>
Output:
Method 2: Using DOM querySelector() Method.
This method is used to select elements in the document. The title element can be selected by specifying the title element in the selector as a parameter. This will return the current title element of the page. The textContent property of an element returns the text content of a specific node. The title of the page can be changed by assigning the required new title as a string to the textContent property. This will change the title of the website to the preferred title.
Syntax:
newPageTitle = 'The title has changed!'; document.querySelector('title').textContent = newPageTitle;
Example:
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to dynamically change a web
page’s title using JavaScript ?
</
title
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>
GeeksforGeeks
</
h1
>
<
b
>
How to dynamically change a web
page’s title using JavaScript ?
</
b
>
<
p
>
Click on the button to change the page
title to: "The title has changed!"
</
p
>
<
button
onclick
=
"changePageTitle()"
>
Change Page Title
</
button
>
<
script
type
=
"text/javascript"
>
function changePageTitle() {
newPageTitle = 'The title has changed!';
document.querySelector('title').textContent
= newPageTitle;
}
</
script
>
</
body
>
</
html
>
Output:
Improve Article
Save Article
Improve Article
Save Article
Given a web page containing the page title and the task is to change the title of a web page dynamically using JavaScript.
Method 1: Using JavaScript document.title property.
This property is used to set or return the current title of the document. The title of the page can be changed by assigning the new title as a string to this property. This will change the title of the website to the preferred title.
Syntax:
newPageTitle = 'The title has changed!'; document.title = newPageTitle;
Example:
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to dynamically change a web
page’s title using JavaScript ?
</
title
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>
GeeksforGeeks
</
h1
>
<
b
>
How to dynamically change a web
page’s title using JavaScript ?
</
b
>
<
p
>
Click on the button to change the page
title to: "The title has changed!"
</
p
>
<
button
onclick
=
"changePageTitle()"
>
Change Page Title
</
button
>
<
script
type
=
"text/javascript"
>
function changePageTitle() {
newPageTitle = 'The title has changed!';
document.title = newPageTitle;
}
</
script
>
</
body
>
</
html
>
Output:
Method 2: Using DOM querySelector() Method.
This method is used to select elements in the document. The title element can be selected by specifying the title element in the selector as a parameter. This will return the current title element of the page. The textContent property of an element returns the text content of a specific node. The title of the page can be changed by assigning the required new title as a string to the textContent property. This will change the title of the website to the preferred title.
Syntax:
newPageTitle = 'The title has changed!'; document.querySelector('title').textContent = newPageTitle;
Example:
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to dynamically change a web
page’s title using JavaScript ?
</
title
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>
GeeksforGeeks
</
h1
>
<
b
>
How to dynamically change a web
page’s title using JavaScript ?
</
b
>
<
p
>
Click on the button to change the page
title to: "The title has changed!"
</
p
>
<
button
onclick
=
"changePageTitle()"
>
Change Page Title
</
button
>
<
script
type
=
"text/javascript"
>
function changePageTitle() {
newPageTitle = 'The title has changed!';
document.querySelector('title').textContent
= newPageTitle;
}
</
script
>
</
body
>
</
html
>
Output:
Как изменять в теге title через javascript
Изменить содержание тега title в javascript. Заменить содержание тега title через js — это очень просто! Чтобы изменение title было живым — мы сделаем скрипт с кнопкой! На странице рассмотрим способ замены значения тега title.
Заменить title через javascript пример
- Заменить значение тега title
- Готовый код замены title через javascript
- Заменить значение тега title №2
Как было уже выше сказано, то мы будем рассматривать замену значения тега title, т.е. того тега title, который идет одним из первых на странице.
Как изменить значение тега title
Для того, чтобы изменить содержание тега title вам понадобится:
Кнопка button — для того, чтобы увидеть вживую замену содержания в теге title
Добавим id — чтобы отследить нажатие по кнопке с помощью onclick
<button id=»the_button»>Нажми на меня!</button>
После того, как мы сделали кнопку, надо обратиться к тегу к title с помощью, например querySelector
var the_title = document.querySelector(«title»);
После этого нам понадобится innerHTML, чтобы заменить значение тега title + onclick и новое содержание — «Привет мир!»:
document.querySelector(«#the_button»).onclick = function (){ the_title.innerHTML = «Привет мир!»; }
Соберем весь код замены значения тега title
Далее нам остается собрать весь код, который будет менять значение тега tittle по нажатию.
Этот вопрос уже перенесем в новый пункт.
Готовый код замены title через javascript
Нам осталось собрать код изменения тега tittle по нажатию.
Html:
<button id="the_button">Нажми на меня!</button>
javascript
<script>
the_title = document.querySelector("title");
document.querySelector("#the_button").onclick = function (){ the_title.innerHTML = "Замени значение тега title #1!"; }
</script>
Результат замены тега tittle по нажатию.
Чтобы увидеть результат изменения тега tittle по нажатию — откройте исследовать элемент и нужно нам найти тег title, как видим внутри у нас title находится текст — Изменить title через js.
Теперь возвращаемся к нашей кнопке и нажимаем Изменить title через js!
Видим результат, что наше содержания тега title изменилось!
Нажмите, чтобы открыть в новом окне.
Заменить значение тега title №2
Для того, чтобы заменить/изменить содержание тега «title» можно использовать другой способ!
Для этого вам понадобится:
Кнопка по которой будем нажимать — button.
В неё добавляем id.
<button id=»the_button_2″>Измени title через js</button>
Тег script.
Используем onclick.
В функцию помещаем «Document.title» с новым значением = «Замени значение тега title #2!».
Соберем весь код:
Код изменения содержания тега title
Html:
<button id="the_button_2">Измени title через js</button>
javascript
<script>
the_button_2 .onclick = function (){document.title = "Замени значение тега title #2!";}
</script>
Выполнение Кода изменения содержания тега title
Для того, чтобы увидеть процесс «изменения содержания тега title» вживую… просто нажмите кнопку «Измени title через js«.
Где посмотреть извинения title? Нажмите исследовать элемент ищите тег <title>
Можете не благодарить, лучше помогите!
COMMENTS+
BBcode
- HowTo
- JavaScript Howtos
- Change the Page Title in JavaScript
Shiv Yadav
Jan 30, 2023
Feb 23, 2022
- Use the
document.title
Property to Change the Page Title in JavaScript - Use the
querySelector()
Method to Change the Page Title in JavaScript
This article will discuss modifying a web page’s title in JavaScript dynamically.
Use the document.title
Property to Change the Page Title in JavaScript
The document.title
attribute is used to set or retrieve the document’s current title. The page’s title can be modified by assigning a new title as a string to this property.
The website’s title will then be changed to the selected title.
Syntax:
newPageTitle = 'Title changed!';
document.title = newPageTitle;
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Dynamically change a web
page's title
</title>
</head>
<body>
<b>
Dynamically change a web
page's title
</b>
<p>
Click on the button to change the page
title to: "title changed!"
</p>
<button onclick="changePageTitle()">
Change Page Title
</button>
<script type="text/javascript">
function changePageTitle() {
newPageTitle = 'title changed!';
document.title = newPageTitle;
}
</script>
</body>
</html>
Output before clicking the button:
Output after clicking the button:
Use the querySelector()
Method to Change the Page Title in JavaScript
We can use the document.querySelector()
method to pick elements in a document.
The title element can be chosen by giving the title element a selector parameter and retrieving the page’s main title element.
An element’s textContent
attribute returns the text content of a particular location. The page’s title can be modified by setting the textContent
property to the required new title as a string.
Syntax:
newPageTitle = 'title changed!';
document.querySelector('title').textContent = newPageTitle;
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Dynamically change a web
page's title
</title>
</head>
<body>
<b>
Dynamically change a web
page's title
</b>
<p>
Click on the button to change the page
title to: "title changed!"
</p>
<button onclick="changePageTitle()">
Change Page Title
</button>
<script type="text/javascript">
function changePageTitle() {
newPageTitle = 'title changed!';
document.querySelector('title').textContent = newPageTitle;
}
</script>
</body>
</html>
Output before clicking the button:
Output after clicking the button:
Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.