The code below makes the first step: add an image with a link to the home-page and an h1 with the name of the document, if there isn’t an h1 already.
I used an html that references a JavaScript file in the <head>
and has a <h1>
tag for the title (this is one of the expectations that I want to make this because of the special characters).
document.write('<a href="rpg.html"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/U%2B2190.svg/25px-U%2B2190.svg.png"></a><br>');
if (document.getElementById(titulo) != null) /*se existir um não titulo... */ {
var nome_do_documento = window.location.href.substring(window.location.href.lastIndexOf('/') + 1); /*colete o nome do documento */
var titulo = nome_do_documento.replace('_', ' '); /*troque _ por um espaço */
var titulo_pronto = titulo.replace('.html', ''); /*apague a extenção do nome */
document.write('<h1 id="titulo">' + titulo_pronto + '</h1>');
}; /*e o nome no topo da pagina */
document.title = "PVP - " + document.getElementById(titulo).innerText; /*coloque o nome do topo da gina como titulo do html */
<h1 id="titulo">kauã</h1>
I expected these steps:
- check if there’s already a h1 with the id of "titulo"; if not then get the document name, remove the extension name and replace "_" with " " and add this to the
<h1 id="titulo">
. If yes, do nothing. - write the inner-text of
<h1 id="titulo">
in the<title>
tag.
I got this result:
2
Answers
When looking for an element by ID, be sure to send it as a string:
In your example the quotes are missing, which is treated as a variable named
titulo
(likely to beundefined
the first timegetElementById()
is called, then set tonome_do_documento.replace('_',' ')
the second time).In your code you have wrong condition in if statement. Change != to ==, surround id string inside getElementById with quotes and the error will be solved.
If you want, this is my quick refactor of your code.