質問

I know this question was asked many times before, however, I never could find this specific setup.

My script is located at the end of the <body> tag and I am executing an alert message with window.onload, so the reason can't be the DOM not having loaded yet.

It is also not a typo or anything, as I cut&paste the same code passage for testing purposes and when not having an interlaced <div> it works just fine.

However, when I put the <div> inside another <div> the return value suddenly changes to null.

I can't really comprehend that behavior.

Here's two code examples to illustrate the issue better:

Working:

<div id="test123"></div>

// returns the div object

window.onload = function() {
alert(document.getElementById("info123"));
};

Not working:

<div id ="charts_container" style="bottom:0px;padding:0px;overflow:auto;position:absolute; top:35px; left:0px; right:0px; background-color:#ffffff;margin-right:0px;" >
    <div id="test123"></div>
</div>

// returns null

window.onload = function() {
alert(document.getElementById("test123"));
};
役に立ちましたか?

解決

Neither example will work. info123 is not test123. You need to use the right id!

Putting an element inside another one will not hide it from the DOM. Either:

  1. You made an error, such as leaving off the > from the previous tag (use a validator) or
  2. You have some other JavaScript that is removing the element before you try to find it
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top