2

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;
}
5
  • 1
    BTW, you should always prefer textContent instead of innerHTML because it's faster and more importantly: it's safer (due to the risk of XSS and other script-injection attacks) Commented Jun 3, 2020 at 2:51
  • a.style.textAlign also doesn't work? Commented Jun 3, 2020 at 2:53
  • a.styles is not a property, maybe try a.style.alignText = "center";, also you can use document.body.append(el, el2, el3) for multiple elements instead. The issue with document.body.replaceChild(a, parr1) is, that it's never appended to the body, so how would you replace it? Commented Jun 3, 2020 at 2:54
  • @IlkyunIm no, it doesn't work, sadly Commented Jun 3, 2020 at 2:57
  • The problem might be your style sheet. Is it possible to add it? Commented Jun 3, 2020 at 6:53

1 Answer 1

1
  1. I would change from where it says document.body.replaceChild(a, parr1); to say document.body.replaceChild(a, this);. There may be an issue with referencing.

  2. For the text alight, try using a.style.textAlign = "center"; rather than a.styles.cssText('align-text: "center;')

Sign up to request clarification or add additional context in comments.

1 Comment

using this doesn't work, and neither style.textAlign it goes to not work at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.