3

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);
2
  • don't use innerText, use textContent or.text() unless you really want the extra innerText whitespace and you only care about CH+IE Commented Jan 7, 2015 at 12:02
  • you should not add thanks in your question but mark as solution the answer you choose Commented Jan 7, 2015 at 13:36

4 Answers 4

7
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

One more, need to add JQ library before app.js
@Bharadwaj — See point three, and the paragraph following it.
2
(function () {
    for (var i = 0; i < 10; i++) {
      var f = document.createElement('p'),
          div = document.querySelector('.test');

      f.innerText = 'Hi';
      div.appendChild(f);
    }
})();

Comments

2

first of all you are referencing jQuery library without including it

$(document).ready(main);

add the 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 to use the developer console of your browser 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);

Comments

0

Several things:

  1. You need to include the jQuery library
  2. Your function is missing a closing }
  3. It's getElementsByClassName, not getElementByClass
  4. If it's just going to be one div, why not use ID instead? Like so:
$(function () {
    for (var i = 0; i < 10; i++) {
        var f = document.createElement('p');
        f.innerText = "Hi.";
        var div = document.getElementById('test');
        div.appendChild(f);
    }
});

jsFiddle

Comments