Using document.write within loops

I am facing an issue with the following HTML code:

<html>
<script>
        function explode() {
                pp = document.getElementsByTagName("a");
                for(i=0;i<pp.length;i++) {
                    document.write(pp[i].href);
                }
        }
</script>

<body>
 <a href="http://google.com">Google</a>
 <a href="http://yahoo.com">Yahoo</a>
 <button onclick="explode()">Explode</button>
<body>

</html>

After executing this code, only the first hyperlink is being printed on my window. Can anyone provide an explanation for this behavior?

Update I have considered the response that document.write resets the page contents. However, I expected to see the last element in the variable pp since all objects are listed within it. Why does it display the first element instead?

Answer №1

If content is added to the document after it has finished loading, a new document will be opened and replace the existing one. While the document is still loading, you can utilize document.write to insert content (for example, within script tags inline with the code). However, after the document has loaded completely, using document.write will automatically trigger document.open to start writing to a new document.

The result obtained from the `getElementByTagName` method produces a live list that gets updated when elements are added/removed from the DOM. Initially, this list will be empty when the first element is written to the document because there are no matching elements in the document at that point.

Answer №2

document.write - will erase the contents of your browser when it encounters document.write for the first time!

You need to combine the values.

Follow these steps:

function burst() {
        pp = document.getElementsByTagName("a");
        var b='';
        for(i=0;i<pp.length;i++) {
            b+=pp[i].href
        }
    document.write(b);
}

http://jsbin.com/buzexuce/2/edit

To demonstrate in reverse direction:

check out what's happening here:

<a href="http://google.com">Google</a>
<a href="http://yahoo.com">Yahoo</a>
<button onclick="burst()">Burst</button>

<script>
var  pp = document.getElementsByTagName("a");
for(i=0;i<pp.length;i++) 
{ document.write(i);}
</script>

(everything works as expected before the dom is ready).

Answer №3

This is the proper way:

console.log(pp[i].href);

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

Using the spread syntax to eliminate a property from an object within a ReactJs element

I'm trying to figure out if it's possible to remove a specific object property using spread syntax when rendering a React component. I want to achieve this without adding too much extra code. Currently, I am utilizing {reset,...inputName} In my ...

Exploring the colors of legend navigation icons in Google Pie charts

Is there a way to customize the color of the navigation links in Google pie charts (specifically the blue text in the bottom right corner)? https://i.sstatic.net/Hk591.png ...

Retrieving a list of numbers separated by commas from an array

Currently, I'm retrieving data from a MYSQL database by executing the following SQL command: SELECT GROUP_CONCAT(MemberMemberId SEPARATOR ',') AS MemberMemberId FROM member_events WHERE event_date = "2000-01-01" AND Eve ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

Strange behavior noticed with Bootstrap accordion

The current behavior of the product specs section is as expected. Clicking on group 1 shows its content, and when clicking on group 2, it minimizes group 1 and displays group 2. However, the issue arises with the next two categories, Usage and Installatio ...

Inoperable await statement within a while loop

Here is my code snippet for the app: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); async function init() { while (true) { console.log("TICK"); await (rl.qu ...

Vue with DevXtreme DataGrid

Currently, I am working on creating a table using DataGrid in Vue. My goal is to populate the table with data from a v-for loop. However, I am facing some challenges in displaying the values such as {{user.name}}, {{user.email}}, and {{rol.name}}. As a beg ...

Error encountered in NodeJS after refreshing the node server

I am currently in the process of developing a web application using Node.js, Express framework, and EJS templates. Below is the code snippet for my server setup: const express = require('express'); const app = express(); const PORT = process.en ...

What mechanisms do chat apps use to detect when a user sends a message and trigger a re-render of the chat

Do I need to implement websockets for my React chat app using MySQL? I'm facing an issue where the app doesn't re-render when I open it in a new tab and type a message. Should I consider using websockets for real-time updates, or are there any ot ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

What is the reason for the error occurring in express.js?

I encountered an issue when I added this snippet of JavaScript to an HTML page being served by express.js. What could be causing the error? <script> var foo = /<%([\s\S]+?)%>/g; </script> Error: 500 SyntaxErro ...

Exploring the functionalities of JavaScript methods and nested components within Vue.js

Learning Vue.js has been an interesting experience for me. However, I am facing challenges with methods and child elements in the library. It seems like there is something simple that I am overlooking. In my current project, I have list items rendered on ...

angular-library.js:6 Uncaught TypeError: Unable to access the 'toLowerCase' property of an undefined value

$scope.searchCat = function(){ $scope.searchArray = []; const searchField = document.querySelector('#search input[type="search"]'); if(searchField){ $scope.searchTerm = searchField.value.toLo ...

problem encountered when closing datepicker

I discovered a clever method to use 2 datepickers after doing some research on this site. When you select a date on the first one, the second datepicker automatically appears with the selected date as the new minDate. You can see this feature in action on ...

Tips for implementing advertisements through a content management system or JavaScript

After reviewing a discussion on how to dynamically change code on clients' websites for serving ads, I am in search of an easy-to-implement solution. The code is frequently updated as we experiment with different ad networks like Adsense. Ideally, I w ...

Struggling with dynamic values and regex while utilizing HTML template strings. Need help overcoming regex challenge

Feeling stuck and seeking advice on improving regex usage. For a one-time substitution, the code below works for replacing a single element like -link-. var testHtmlStr = '<tr>' + '<td class="eve"><div class= ...

Adding a value to an element in JavaScript to interact with it using Selenium

After implementing the provided code snippet, I noticed that it replaces the value in the element with a new one. However, I am looking to append or insert a new line rather than just replacing the existing value. Is there an alternative command like app ...

Is there a way to incorporate an array into an array of arrays with jQuery?

I am working with an array shown below: var cString = [ ['1','Techdirt','www.techdirt.com'], ['2','Slashdot','slashdot.org'], ['3','Wired&apos ...

Scheduled tasks arranged by the user

My goal is to empower my users to schedule specific actions at their preferred times. With a node server hosted on Azure, I am exploring the potential of using node-schedule for this functionality. One idea I'm considering is running a master schedule ...

Using Delta encoding to optimize JSON objects

Are there any standard libraries or tools available for calculating and applying differences to JSON documents? I have several large documents that need to be synchronized across a network, and I don't want to resend the entire state each time I sync ...