0

Hi is there a way to make the appended "YAY" be of a different style from the "I am happy" text? eg. bigger font-size/ bolded.

document.getElementById("appendButton").onclick = function() {

  document.getElementById("happy").innerHTML += " YAY";

}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>

I've tried to give it an id with span, but then the button won't append anything. Would appreciate any help thanks!

yijiyap
  • 17
  • 3
  • 1
    Just create an empty span inside the happy id: `

    I am happy

    ` and then target "cheer" in your onclick instead of "happy".

    – Mordred Nov 19 '21 at 04:32

2 Answers2

1

You won't be able to use an id because ids must be unique (which means you can't have more than one on a page and expect the correct output).

Add a class instead.

Note 1: I've used the more modern addEventListener method here.

Note 2: It's also worth mentioning that concatenating HTML strings to innerHTML is considered bad practice. insertAdjacentHTML is the better alternative.

const button = document.getElementById('appendButton');
const happy = document.getElementById('happy');

button.addEventListener('click', handleClick, false);

function handleClick() {
  happy.innerHTML += '<span class="yay"> YAY</span>';
}
.yay { color: blue; font-weight: 600; }
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
Andy
  • 61,948
  • 13
  • 68
  • 95
1

You can append a span element with a class, then style it with CSS:

document.getElementById("appendButton").onclick = function() {
  document.getElementById("happy").innerHTML += "<span class='large'>YAY</span>";
}
.large{
  font-size:20px;
  font-weight:bold;
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
Spectric
  • 30,714
  • 6
  • 20
  • 43