Why setAttribute() doesn't work here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
18th Jul 2019, 7:40 AM
Merida
Merida - avatar
2 Answers
+ 10
The JS error is due to the script executing before the document is properly loaded. Try: window.onload = function() { var h1 = document.getElementsByTagName("h1")[0] h1.setAttribute("title","good"); }
18th Jul 2019, 7:45 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Your DOM is not ready at the moment. Wrap your code with document.addEventListener('DOMContentLoaded', function(){ //Your code });
18th Jul 2019, 7:51 AM
FedorT
FedorT - avatar