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

Exploring the functionality of placeholders within jQuery

I am trying to create a customizable text template where I can insert placeholders and then fill those placeholders with data to use on my page. For example: var template = '<div class="persons">'; template += '<p> <span clas ...

Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, ...

Exploring the world of JSON manipulation in JavaScript

I've been experimenting with JSON recently and came across something I don't quite understand. Here is an example of some code I used: var str = "{'name':'vvv'}"; var cjson = eval ("(" + str + ")"); alert( ...

Getting a specific index from an array using the Angular ng-repeat Directive: A step-by-step guide

I am trying to retrieve a specific index in an array using the ng-repeat directive. Currently, it is displaying information for all indexes... I only want to display the information for the second index as an example... This is my main.js: app.controll ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

The onClick event cannot be triggered within a div that is generated dynamically

I am having an issue with a jquery code that dynamically generates a div. The problem I'm facing is that the onclick function for the anchor tag is not calling the required function. Below is the code snippet: $("#new").append(' <ul cla ...

What is the process for integrating Internet Explorer 10 compatibility into a basic VueJs component?

I am facing an issue with a VueJs component that is not rendering in IE 10. Context: The Vue component I am working on is a company events list with basic filtering and sorting functionalities. Unfortunately, IE10 support is required for this project. Eve ...

Switching visual content according to dropdown choice

Hey there! I've been working on my HTML file and ran into a little issue. I'm trying to change the image in the div section based on a dropdown selection that modifies the source of the image from an XML file. However, I keep getting an error tha ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

A tutorial on dynamically adding fields with a dropdown list (populated from a database) and a text box using PHP and JQuery

I have multiple form components that I need to add dynamically, allowing users to add more than one. Firstly, there is a dropdown list with values populated from MySQL, followed by a text box for inquiries entry. The dropdown list displays a list of users, ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

Using Node.js, we can create a program that makes repetitive calls to the same API in a

My task involves making recursive API calls using request promise. After receiving the results from the API, I need to write them into an excel file. Below is a sample response from the API: { "totalRecords": 9524, "size": 20, "currentPage": 1, "totalPage ...

Incorporating Material-UI with React Searchkit for a seamless user experience, featuring

I encountered an issue when trying to use both searchkit and material-ui in my React application. The problem arises from the fact that these two libraries require different versions of reactjs. Initially, everything was working fine with just searchkit in ...

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

The absence of text is not displayed in an empty slot of a Buefy table

Currently, I am working on a Nuxt project with Buefy implementation. I attempted to create a table with an #empty slot that displays a message when no data is available. However, my code does not seem to be working as expected. If you refer to the Buefy do ...

How do the scopes of a controller and a directive's controller differ from each other?

Can you explain the difference between a controller and a directive's controller in terms of scope? I'm struggling to grasp the distinction and whether it's necessary to create controllers within the DDO for my directives. In the code snipp ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

What is the best way to save newly added elements on a webpage that were submitted by the

I am looking for a way to save the changes made by users on my webpage so that they can navigate to different pages and come back without losing any added elements. These changes should be retained even when the user goes back to edit the webpage, but I pr ...