I am trying to do a game menu on javascript, I'm generating HTML with javascript because of practice.
I got this event listener that I should click to obtain the lhyperlink to another page, but when it appears, the hyperlink instead of getting centered by CSS stylesheet, it goes default and gets to the left.
I don't know how it's called in CSS
Here's my code:
const h1 = document.createElement("h1");
const parr1 = document.createElement("p");
const parr2 = document.createElement("p");
body.appendChild(h1);
body.appendChild(parr1);
body.appendChild(parr2);
h1.innerHTML = "Aventura D&D";
parr1.innerHTML = "Empezar Juego";
parr2.innerHTML = "Cargar juego";
parr1.addEventListener('click', (event) => {
let a = document.createElement('a');
let link = document.createTextNode('Juego Nuevo');
a.appendChild(link);
a.title = "Juego Nuevo";
a.href = '/game1.html';
//Here is the problem!!!!
document.body.replaceChild(a, parr1);
});
I went to the Element Inspector and I was able to modify the element by modifying the body tag. Why?
Here is the CSS sheet
body{
background: black;
color: goldenrod;
//This is the part that is working but I wonder why if the spawned //hyperlink should obey <a> tag
text-align: center;
}
h1{
font-size: 9em;
font-family: 'Courier New', Courier, monospace;
color: #c90000;
text-align: center;
}
p{
font-size: 3em;
text-align: center;
}
a{
font-size: 3em;
}
textContentinstead ofinnerHTMLbecause it's faster and more importantly: it's safer (due to the risk of XSS and other script-injection attacks)a.style.textAlignalso doesn't work?a.stylesis not a property, maybe trya.style.alignText = "center";, also you can usedocument.body.append(el, el2, el3)for multiple elements instead. The issue withdocument.body.replaceChild(a, parr1)is, that it's never appended to the body, so how would you replace it?