Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use javascript for html?

I'm a beginner of Javascript and html. I want to output 10 "Hi" but following code doesn't work. What should I do?

index.html and app.js is in a same folder.

index.html

<html>
<head>
</head>
<body>
<div class = "test"></div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

var main = function(){
for(var i = 0; i<10; i++){
    var f = document.createElement('p');
    f.innerText = "Hi.";
    var div = document.getElementByClass('test');
    div.appendChild(f);
};
$(document).ready(main);

1 Answers

  1. Look in your browser's JavaScript error console
  2. See the error about $ being undefined and thus a reference error
  3. Define $ (which you probably want to do by including the jQuery library)

Alternatively, just get rid of $(document).ready(main); and call main() directly instead. You don't appear to have any need for jQuery in there.

You'll then have to contend with getElementByClass not being a function. See getElementsByClassName or querySelector instead.

like image 102
Quentin Avatar answered Jan 03 '26 10:01

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!