Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append text of different style

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading