user4833724
user4833724

Reputation:

Text won't show up using innerText or innerHTML

as the title said and i'm learning javascript and still a beginner.
This the Html file here :

<!DOCTYPE html>
<html>
<head>
 <title>jQuery</title>
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
  <h1 class="menu"></h1>
  <script type="text/javascript">
   function clr(o){
    var a1 = [];
    var i = 0;
    for (var k in o){
        a1[i] = 0;
        i++;
    }
    return a1;
   }
   console.log(clr({a:"a", b:"b", c:"c"}));
   document.getElementsByClassName("menu").innerText = clr({a:"a", b:"b", c:"c"});
  </script>
</body>
</html>

Upvotes: 2

Views: 1111

Answers (3)

Vincent Toonen
Vincent Toonen

Reputation: 74

I edited a couple a things. You were close. I gave the h1 an id. And used document.getElementById.

<!DOCTYPE html>
<html>
<head>
 <title>jQuery</title>
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
  <h1 id="menu"></h1>
  <script type="text/javascript">
   function clr(o){
    var a1 = [];
    var i = 0;
    for (var k in o){
        a1[i] = 0;
        i++;
    }
    return a1;
   }
   console.log(clr({a:"a", b:"b", c:"c"}));
   document.getElementById("menu").innerHTML = clr({a:"a", b:"b", c:"c"});
  </script>
</body>
</html>

Upvotes: 1

nem035
nem035

Reputation: 35481

document.getElementsByClassName("menu") will return an Array-like NodeList of elements that contain the class menu.

Since its an Array-like object, you need to access individual elements using [].

In your case, it will be a an array of 1 element, the h1 element, so to access it you need to grab it at position 0:

document.getElementsByClassName("menu")[0].innerHTML = clr({a:"a", b:"b", c:"c"});
----------------------------------------^

Upvotes: 1

Steeve Pitis
Steeve Pitis

Reputation: 4443

Since you are running Jquery you can use Jquery method. like text() or html()

But your problem, is that document.getElementsByClassName("menu") return an HTML Collection so you have to do : document.getElementsByClassName("menu")[0].innerHTML

<!DOCTYPE html>
<html>
<head>
 <title>jQuery</title>
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
  <h1 class="menu"></h1>
  <script type="text/javascript">
   function clr(o){
    var a1 = [];
    var i = 0;
    for (var k in o){
        a1[i] = 0;
        i++;
    }
    return a1;
   }
   console.log(clr({a:"a", b:"b", c:"c"}));
   $(".menu").text(clr({a:"a", b:"b", c:"c"}));
  </script>
</body>
</html>

Upvotes: 1

Related Questions