the document is exhibiting curious behavior

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Title</title>
        <script language="JavaScript">
        <!--
        function displayTags()
        {
            var tag, tags;
            
            tags = "Here are the tags in the page:"
            for(i = 0; i < document.all.length; i++)
            {
                tag = document.all(i).tagName;
                tags = tags + "<br>" + tag;
            }
            document.write(tags);
        }
        //  -->
        </script>    
    </head>
    <body onload="displayTags()">
        <h1>My <b>Website</b></h1>
    </body>
</html>

output:

Here are the tags within this webpage:
HTML
HEAD
META
BODY
H1
B

If I uncomment the first document.write() line, the output changes to:

The tags on this page are:
HTML
HEAD
BODY

It seems that some tags are missing. Where could the mistake be? Thank you in advance.

Answer №1

The reason for this issue is that when document.write is executed after the document has finished loading, it replaces the current document entirely. This behavior occurs because of the presence of onload="showtags()". To prevent this from happening, document.write should be called before the DOM is fully loaded. For instance:

<p> <script> document.write("hi"); </script> </p>

This example is acceptable since the DOM is still in the process of loading. However, executing document.write within an onload function or after the page has finished loading will lead to issues.

Answer №2

After the completion of the document loading process, every time you use document.write(), it wipes out the existing content and initiates a new blank document, erasing anything that was previously present in the document.

Since you're invoking this function within an onload handler, it confirms that the document load has finished, leading to a fresh start with your document.write() creating a new document.

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

Building/Deleting the Vue Component using text search

In my App.vue file, I have the following setup: <template> <div id="app"> <input type="text" v-model="term"> <hello-world text="Button 1" v-if="term === ''"></hello-world> <hello-world ...

The filtering function using jQuery and ajax

Hello, I'm currently working on a website that compares the prices of domain names. I could use some assistance with a specific function that I'm trying to implement. At the moment, there is a section on the website where users can click on dif ...

Is there a way to determine the names of the functions that are being called?

I'm working on mastering Google Development Tools. Is there a way to determine which specific functions, especially those in Javascript, are needed before a page can load successfully? ...

Tips for integrating Tailwind CSS into Create React App using React

I recently started using tailwindcss with my react app. I tried to follow the guide from tailwindcss but encountered various issues and bugs along the way. If anyone has advice on how to successfully start a project using tailwind and react, I would apprec ...

What is the best way to update and override multiple nested NPM dependencies with various versions?

Apologies for not being fluent in English Here is my NPM dependency: dependency tree +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c1e090d0f184108091a4105021f1c090f18031e2c5d4255425c">[email protected]</a> ...

arrange list in Angular.js

Currently, I am attempting to sort an array using Angular JS with the orderBy function. However, I am experiencing difficulties sorting it based on a specific key. Below is the code snippet: var app = angular.module('sortModule', []) app.contr ...

Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To b ...

Whenever I'm rendering my handlebars template, it unexpectedly gets terminated on its own

I have encountered an issue with my handlebar template. For some reason, a closing tag is being automatically inserted just before any closing tag in the template, causing it to be recognized as plain text. If you visit the following page: For example: { ...

Losing the properties of a component when employing the 'as' styled-component attribute on an extended styled-component

I created a CallToAction component as follows: const CallToAction = ({ text = "Default text" }) => ( <S_CallToAction>{text}</S_CallToAction> ) const S_CallToAction = styled.div` // Some styles... ` export default CallToAction ...

Resetting the value of an object property

My query concerns a provider: AdviceList.provider('$adviceList',function(){ this.$get = function ($rootScope,$document,$compile,$http,$purr){ function AdviceList(){ $http.post('../sys/core/fetchTreatments.php'). ...

Incomplete Loading of Google Maps

Let me clarify that the solutions I have come across so far have not been successful. I am attempting to display a modal alert with a basic Google Maps integration. Problem: Google Maps does not load completely. Snippet from my .js file: var map; functi ...

Angular UI Accordion with full-size clickable panels available for interaction (?)

I'm facing a simple issue and I can't figure out why I'm not getting the desired behavior. I am currently utilizing the Angular UI Bootstrap accordion, however, in the provided example, the only way to open the accordion is by clicking on th ...

Exploring the power of AngularJS factory promises with the use of Pouch

After creating a service to retrieve data from a local json file, I proceeded to integrate this service with my controllers. However, I recently discovered how to fetch the same data from a pouchDB database. $scope.healthSystems = HealthSystemData.get(); ...

Establish the starting time for the timer and use the setInterval() function according to the seconds stored within the object

How can I configure the values of timerOn, timerTime, and timerStart to make the watch start counting from 120 seconds? Currently, the clock starts counting from 3 minutes and 22 seconds, but it should start from 2 minutes. You can find all the code here: ...

Creating scrollable content using JavaScript within a container with a hidden overflow

I am looking for a solution to efficiently display numerous image thumbnails within a limited space. My plan is to organize the thumbnails into 3 columns with an undetermined number of rows. I intend to place this content inside a viewport div, structured ...

What is the best way to patiently wait for lines to be printed out one by one

I am in the process of creating my own personal website with a terminal-style design, and I'm looking to showcase a welcome banner followed by a welcoming message. The effect I have in mind involves lines appearing individually from top to bottom and ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...

Can you help me with sorting asynchronous line points for KineticJS?

For the past couple of days, I've been grappling with a peculiar issue that I found difficult to articulate in the title. The challenge I'm facing involves a KineticJs Line, which contains an array of points (line.attrs.points) represented as ob ...

What could be causing the data to not load from the database when the page is loaded?

My current setup involves a button that triggers a specific function upon loading. return ( <> <LikeButtonStyle onLoad={getUserData} onClick={addInfo}> <Image width="10px" height="auto" src="/ ...

AngularJS: Organizing Controllers Horizontally Within ngRepeat

My data consists of a table with 100 rows, each representing a complex object that is an instance of a specific type. User interactions trigger operations on these objects individually, with each row having unique operations independent of the others. $sc ...