How can I use javascript for html?
I am a Javascript and html beginner. I want to output 10 "Hi" but the following code doesn't work. What should I do?
index.html and app.js are in the 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);
source to share
- Look in your browser for the JavaScript error console
- See error message
$
undefined and thus reference error - Define
$
(which you probably want to do by including the jQuery library )
Alternatively, just get rid of $(document).ready(main);
and call main()
directly. You don't seem to have any need for jQuery.
Then you have to fight with getElementByClass
non-function. See getElementsByClassName
or querySelector
.
source to share
you are linking to the jQuery library in the first place without including
$(document).ready(main);
add link to jquery library:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
then your script has some errors:
try using your browser's developer console to debug it
your code should look like this:
var main = function(){
/*no need to exec this for all loops iteration
and the right method is getElementByClassName not getElementByClass */
var div = document.getElementByClassName('test')[0];
for(var i = 0; i<10; i++){
var f = document.createElement('p');
f.innerText = "Hi.";
div.appendChild(f);
};
} /*you forgot to close the function*/
$(document).ready(main);
source to share
A few things:
- You need to include jQuery library
- Your function is missing a closure
}
- This
getElementsByClassName
, notgetElementByClass
- If it's only going to be one div, why not use ID instead? For example:
$(function () {
for (var i = 0; i < 10; i++) {
var f = document.createElement('p');
f.innerText = "Hi.";
var div = document.getElementById('test');
div.appendChild(f);
}
});
source to share