Sander Langens
Sander Langens

Reputation: 13

Javascript doesn't add the class

I just started learning javascript and i have a piece of code that is not working and i can't figure out what is wrong.

I have already checked the names of everything if they are spelled correctly multiple times.

function beautify() {
  document.write("ja");
  var item = document.getElementById("top");    
  item.classList.add("beautiful");
  return;
}

Upvotes: 0

Views: 51

Answers (2)

SpeederX
SpeederX

Reputation: 404

To debug the code and try to understand the problem, i would use console.log().

function beautify(){ 
        console.log('function is executed');
        document.write("ja");
        var item = document.getElementById("top");  

        item.classList.add("beautiful");
        return;
}
beautify();

So you execute the function - by calling function_name(); - after you have declared it, and check if the console.log() writes something through your browser console. For example on Firefox or Chrome by pressing F12 you can access it.

EDIT: I forgot to mention you can also see Javascript errors through the console in case

Upvotes: 0

Manish Khedekar
Manish Khedekar

Reputation: 402

Please refer to https://javascript.info

A very good website to refer.

document.body.innerHTML = "<button onclick='beautify()'>Click Me</button>"; 
document.body.innerHTML += "<h1 id='top'>Manish</h1>"; 

function beautify()
{ 
var item = document.getElementById("top");  
item.classList.add("beautiful");
}
.beautiful{
  color:red;
}

Upvotes: 1

Related Questions