How to take the title of an HTML page and return its value in Javascript

Asked

Viewed 1,700 times

1

I need to know exactly how to return the page title value:

<title> nome </title>

Returning in this way:

you are on the page 'name'.

I’ve seen a question related to a few years but I couldn’t.

3 answers

3


Just use the property title in document. You can also use this property to change the title of the page.

console.log(`Você está na página '${document.title}'`);    
console.log('Você está na página ' + document.title); // Sem string template

document.title = 'Novo Título'; // Alterando o título
console.log(`Agora o título da página é '${document.title}'`);
<title>Teste</title>

See more in document.title on MDN.

  • it is displaying '${Document.title}' as part of the text. but it does not present the title itself

  • @J.Rodrigues You’re probably using quotes instead of backticks (```) to wrap the string

  • @J.Rodrigues Anyway, this is secondary in the question. If the interpolation does not work, just make a simple concatenation.

  • Valew guy now worked, had never used this key.

  • @J.Rodrigues I noticed that you marked the answer as correct and then canceled. There’s something wrong with the answer?

  • I don’t know what happened because it’s correct, maybe a problem in the app

  • @J.Rodrigues I think you tried to mark two answers as correct. Even though there are several right answers to your question the site only accepts one of them to be checked. I don’t think you knew this.

  • sorry, I am new in both the programming and the system of the site. thank you for informing me, I will keep this reply as correct.

Show 3 more comments

2

You have to use javascript for this:

Applying the following code, for example:

document.getElementById("seuelemento").value = document.title;

you assign the title value to a field with id "your element"

As an example

 <input type='text' id='seuelemento'>

the exact javascript code to get the title name of a page is:

document.title

0

You can use the DOM function: getelementsbytagname and access the internal content of this TAG.

document.getElementsByTagName("title")[0].innerHTML

The difference is that this function returns a vector with all elements of tag type specified.

And consequently you will have to manipulate the correct index of that target element.

  • This will return a "Undefined". As you yourself quoted in the answer, it will return a "vector", therefore, to capture the value of the tag, you must pass "index". The correct is document.getElementsByTagName("title")[0].innerHTML

  • Yes, correct. As I mentioned vector, it assumes that somehow you have to manipulate index. I will do the editing needed to improve the answer. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.