-1

This is my code:

<html>
<head>
  <title>Demo</title>
  <script>
    function show()
    {
      var content = document.getElementById("content");
      var sub = content.getElementById("sub1");
      alert(sub.nodeName);
    }
  </script>
</head>
<body>
<div id="content">
  <div id="sub1">
    Content 1
  </div>
  <div id="sub2">
    Content 2
  </div>
  <input type="button" value="Click" onclick="show()" />
</div>
  </body>
</html>

Why don't the content.getElementById and alert functions work? Thank for answer.

loithuxua
  • 25
  • 1
  • 4
  • 4
    Because there is no `sub1` id. You could do `console.log(sub)` and discover what happens. Or just look at your JavaScript console, it would tell you that `sub` is `null`. – Jon Jun 19 '13 at 15:09
  • 1
    Just to be clear `class` (`document.getElementsByClassName()`) !== `id` (`document.getElementById()`). – David says reinstate Monica Jun 19 '13 at 15:09
  • 1
    Why do you get `content` in the first place? Since ids should be unique, you can use `document.getElementById` for any id. There's no need to "narrow it down" like that. – David Jun 19 '13 at 15:10

2 Answers2

9

You have a class of sub1, no ID of sub1

Change

<div class="sub1">

To

<div id="sub1">

Also change:

var sub = content.getElementById("sub1");

To:

var sub = document.getElementById("sub1");
tymeJV
  • 99,730
  • 13
  • 150
  • 152
  • thank, but it still doesn't work, this is error TypeError: content.getElementById is not a function – loithuxua Jun 19 '13 at 15:11
  • See edited answer, `var sub = content.getElementById("sub1");` is the problem issue. – tymeJV Jun 19 '13 at 15:11
  • 3
    @loithuxua: `getElementById` is a function of the `document` object. – Felix Kling Jun 19 '13 at 15:11
  • @FelixKling as you say, some_element.getElementByid will no work? – loithuxua Jun 19 '13 at 15:13
  • 1
    @loithuxua: Yes. Since IDs are supposed to be unique in the document, there is no need to give every element this method. – Felix Kling Jun 19 '13 at 15:38
  • @FelixKling thank you, Do W3C explain this problem? – loithuxua Jun 19 '13 at 15:41
  • 1
    @loithuxua: You can have a look at the [`Document` interface definition](http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document) and the [`Element` interface definition](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614). [Here is the definition of the ID attribute](http://www.w3.org/TR/html4/struct/global.html#adef-id). – Felix Kling Jun 19 '13 at 15:44
  • @FelixKling Thank you very much! – loithuxua Jun 19 '13 at 15:47
0

Use var sub = content.getElementById("sub1"); Remember the E,B and I are capital letters

And use alert(sub.innerHTML);

P Ravikant
  • 989
  • 2
  • 10
  • 27