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

How do I make the label text of an element bold in javascript?

My HTML :

<div id="PDF">
    <input type="checkbox" id="pdf" name="pdf" value="pdf">
    <label for="pdf">PDF</label>
</div>

My JS :

document.addEventListener('change',function(event){
    if(event.target.id == "pdf"){
        if(event.target.checked == true){
            event.target.label.style.fontWeight = "bold";
        }
        else{
            event.target.label.style.fontWeight = "normal";
        }
    }
});

To my utter dismay, when I execute the code, I am greeted with this error:

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

Uncaught TypeError: Cannot read properties of undefined (reading
‘style’)

How do I fix this issue?

>Solution :

There are two main issues here. Firstly, the event target has no attribute of label. You should just select the label explicitly and change the styles. Secondly, I would recommend adding the event listener to only the #pdf div rather than the whole document. This way, you won’t need to check for the ID and the event listener won’t be fired on every change. For example:

document.getElementById("pdf").addEventListener("click", event => {
  const label = document.querySelector("label[for=pdf]");
  if(event.target.checked == true){
    label.style.fontWeight = "bold";
  }
  else{
    label.style.fontWeight = "normal";
  }
})
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