What causes the discrepancy in the output of `document.documentElement.childNodes` in JavaScript?

While working on my code exercise today, I came across a special case regarding the "document.documentElement.childNodes" property. Originally, I believed it to represent all child nodes within a tag as before. However, when implementing my code, I noticed a discrepancy:

<!DOCTYPE html>
<html>
<head>
<title>javascript</title>
<script>
    var o = document.createElement('script');
    o.text = 'alert("111")';
    var ohtml = document.documentElement;
    alert(ohtml.nodeName); //output HTML
        alert(ohtml.childNodes.length); //nodes length is 1
    alert(ohtml.childNodes.length); //just head
    ohtml.childNodes[0].appendChild(o);
    function shownode() {
        var ohtml = document.documentElement;
        alert(ohtml.nodeName);
        alert(ohtml.childNodes.length);  //nodes length is 3
        alert(ohtml.childNodes[0].nodeName); //head 
        alert(ohtml.childNodes[1].nodeName); //#text 
                alert(ohtml.childNodes[2].nodeName); //body 
    }
</script>
</head>
<body><div>test</div><input id="Button1" type="button" value="show nodes" onclick="shownode();" />
</body>
</html>

I am puzzled by the fact that executing "document.documentElement.childNodes" in a tag and within a function yields different results. Can anyone provide more examples or insights on this topic? Thank you!

Answer №1

The key is to implement it within a head script tag so that when it runs, the entire DOM has not yet been loaded on the page. When you invoke the function, such as in the console, the DOM is fully loaded. To ensure this, all of your code should be moved to a window.onload event like so:

window.addEventListener("load", function () {
    var o = document.createElement('script');
    o.text = 'alert("111")';
    var ohtml = document.documentElement;
    alert(ohtml.nodeName); //output HTML
    alert(ohtml.childNodes.length); //nodes length is not 1
    alert(ohtml.childNodes.length); // not just head
    ohtml.childNodes[0].appendChild(o);
});

If you prefer not to use the window.onload event, you can simply place it inside the body tag:

<body>
<!--your content-->
<script>
    alert(ohtml.nodeName); //output HTML
    alert(ohtml.childNodes.length); //nodes length is not 1
    alert(ohtml.childNodes.length); // not just head
</script>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The app in NextJs encounters layout issues on all pages due to a break in

I've developed a NextJs application using npx create-next-app and attempted to implement my own custom layout. However, this resulted in breaking the app unexpectedly without any clear reason. The project structure includes: components -> Footer.j ...

Utilize AngularJS's OrderBy feature to iterate through the list for navigation in ascending order by Index

I am looking to customize the order of an Object-array using ng-repeat based on their index keys in ascending order. $scope.paneContainer = {books:[{}] } ; $scope.paneContainer.books[0].science = { title:"science", content:"web/app/views/partials/scienc ...

Performing an AJAX call in Rails 4 to update a particular value

I have a voting button on my website that displays the number of votes and adds an extra vote when clicked. I want to implement Ajax so that the page doesn't need to refresh every time a user votes. However, I am new to using Ajax with Rails and not s ...

Tips for including information in a chart

I'm facing an issue with my current code as it is not functioning properly. Here is the link to the current output: http://jsfiddle.net/4GP2h/50/ ...

Utilizing jQuery to apply multiple classes simultaneously?

What is the purpose of allowing multiple classes to be added? Is there any real benefit to this feature or is it just unnecessary complexity? I attempted to utilize it, but found that it serves no practical function. ...

Transferring an array from PHP to JavaScript via an Ajax response

Welcome to my first post on stackoverflow. I usually find answers from existing posts, but this time I'm facing a problem that none of the suggested solutions have been able to fix. Currently, I have a JavaScript function that makes an AJAX request t ...

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

Enhance the Facebook Login popup with personalized settings

When a user clicks, a popup is triggered: FB.login(function () { // My CallBack }, { scope: 'email,user_birthday,user_location,user_hometown' }); This generates a Facebook login link with multiple parameters. I desire to inc ...

A step-by-step guide on utilizing links for downloading PDF files in Vue/Nuxt

Having some trouble opening a PDF tab in my Vue application with NUXT and Vuetify... any suggestions? I attempted to use: <a href="../static/docs/filename.pdf" target="_blank">Download PDF</a> I also tried using <nuxt-link> but it didn ...

Using JavaScript and Tampermonkey to convert strings from an HTML element into an array

I am trying to change the names of months into numbers and place them in a table cell on a website. I thought using an array would make it easier to reference the month names by their corresponding array numbers, allowing me to add table tags before and af ...

Page load triggers background color shift

Here is the structure of my markup: <div class="authentication"> <div class="form-inputs"></div> </div> My goal is to have the color of the authentication section slide down from top to bottom when the page loads. Initially, the ...

Error: Unable to set value on Vuejs key - the target is read-only

Currently, I am utilizing a combination of Laravel9 with Vuejs3. In one of my blade views, I pass PHP variables to a Vue component like so: <subscription-form location="{{ $props['location'] }}" orientation="{{ $props['ori ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

Error 4 encountered when attempting to upload files using Ajax to a PHP server

On my website, there is a form that looks like this: <form style="width:100%; clear:both; margin-top:50px; background:#fff; border:1px solid green" id="upload_form" enctype="multipart/form-data" class="form" action="" method="post"> <fieldse ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

What is the best way to ensure the alignment of list content and numbering remains separate in HTML while using list-style-position set to inside?

Below is a list with customized styling: ol { background: #ff9999; padding: 20px; list-style-position: inside; } ol li { background: #ffe5e5; padding: 5px; } <ol> <li>Coffee</li> <li>Tea</li> <li>Coca ...

A guide on invoking a Struts 2 action with a different parameter for each row in a jQuery DataTable

Currently, I am working on a JAVAEE project that involves the use of Struts 2 and jQuery DataTable. In this project, I need to add a link with each row in the DataTable that will call an action based on the row's ID. Below is the HTML code for this s ...

The MaterialUI table pagination feature is experiencing an issue where the "Next" button is

Every time I attempt to search for a record with a lower value, such as 6, 14, 19, or 20, the Next button does not become active. However, when dealing with larger records, it functions perfectly fine. I am uncertain about what mistake I might be making. ...