Get div id inside another div id with JavaScript

Edited to explain page loading

My HTML page has a div inside another div, both referenced by id, and both unique throughout the document.

<head>
<script type="text/javascript" src="myscript.js"></script>
</head>
...
<body onload=display()>
<div id="rightwork">
<div id="mychart" > </div>
</div>
...

My JavaScript is meant to write something within the 'mychart' div, but I can't manage to reference it :(

The question is related to this one except this one is a class inside an id.

This is my javascript:

function display() {
    var code = "<a onclick="second(); return false;" href="#">Hello</a>";
    document.getElementById('rightwork').innerHTML = code;
}

function second() {
    console.log(document.getElementById('rightwork'));
    console.log(document.getElementById('mychart'));
}

The line

document.getElementById("mychart");

returns null...

Whereas, this one works fine!

document.getElementById("rightwork");

This returns the expected div.

I attempted this

document.getElementById("rightwork").getElementById("mychart");

which of course does not work as getElementById("rightwork") returns a single element.

So, what's the solution to reference the inner div?


Just use

window.onload = function(){
   var myChart = document.getElementById("mychart");
   // ... code that loads chart
}

Or move

<script type="text/javascript" src="myscript.js"></script>

to the page footer to insure the dom is loaded before running the script


Could you please post whole myscript.js content. If document is loaded correctly why document.getElementById("mychart"); would not work?

The thing might be that <div id="mychart" > </div> is not loaded while javascript is executed and <div id="rightwork"> was loaded in that time.

To ensure the document is fully loaded put your <script type="text/javascript" src="myscript.js"></script> at the end of html.

链接地址: http://www.djcxy.com/p/88022.html

上一篇: 如何在Internet Explorer中容纳巨大的URL?

下一篇: 使用JavaScript获取另一个div ID内的div ID