-1

I have a Javascript project that I am working on that tests a string to see if it's a palindrome and that displays an answer

function displayResult(test) {
console.log('displayResult called on', test)
if(palindrome(test)){
    console.log('it is a palindrome!')
    document.getElementById('answer').innerHTML ="<h2 id='rightAnswer'> You made a palindrome!</h2>"
} else {
    console.log("that's not a palindorm you dumbass")
    document.getElementById('answer').innerHTML ="<h2 id='wrongAnswer'> Boy... you screwed that up</h2>"
}

}

As you can see above, the function inserts an H2 tag that includes an ID for either #rightAnswer or #wrongAnswer then I have CSS that I want to set up to edit both answers.

 #wrongAnswer h2{
    color: red;
}

#rightAnswer h2{
    color: green;
}

However, when I test the code above, it doesn't show the answer as red or green. Is it possible to set up my CSS file to target IDs that are inserted by JS? I'd like to avoid using inline styling if possible.

David Reke
  • 535
  • 1
  • 5
  • 20
  • First, your css look wrong to me, actually you are applying color to an H2 tag inside somethin that have id worngAnswer or rightAnser. Look at this : https://www.w3schools.com/cssref/css_selectors.asp . What the element refered by id answer look like? – Elie Morin Feb 28 '20 at 14:41

4 Answers4

2

change the css selectors

h2#wrongAnswer {
    color: red;
}

h2#rightAnswer {
    color: green;
}

what you wrote mean "select the h2s that have #wrongAnswer or #rightAnswer as ancestor"

asdru
  • 1,147
  • 10
  • 19
1

All you need is just the id

#wrongAnswer{
    color: red;
}

#rightAnswer{
    color: green;
}

What your original CSS was saying was

Style a h2 which is a sub-element of something which has the id wrongAnswer

 #wrongAnswer h2{
    color: red;
}

Style a h2 which is a sub-element of something which has the id rightAnswer

#rightAnswer h2{
    color: green;
}
Simon Long
  • 1,310
  • 4
  • 20
  • 39
1

There is no difference in nodes that are inserted by JS and nodes that were already in your HTML in terms of CSS selectors. CSS works the same either way.

The issue here is that your CSS is incorrect.

#wrongAnswer h2 will select any h2 that is a descendant of #wrongAnwer. In this case, it would probably make sense just to remove h2 from your CSS as an ID should be unique, ie:

#wrongAnwer {
  color: red;
}
stjns
  • 1,420
  • 13
  • 16
1

Your Css is strong following your html, your code will look for something like

<element id="wrongAnswer">
    <h2>

While should look for something like it

<h2 id="wrongAnswer">

So to fix that your css should be

h2#wrongAnswer {
    color: red;
}

h2#rightAnswer {
    color: green;
}
Diego Vinícius
  • 2,125
  • 1
  • 12
  • 23