Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){
  const tree = document.createDocumentFragment();
  const link = document.createElement('a');
  for(let index = 0; index < urlList.length; index++){
    link.appendChild(document.createTextNode(urlList[index]));
    link.setAttribute("href", urlList[index])
    link.setAttribute("id", "link "+index)
    tree.appendChild(link);
    document.getElementById("hyperlinks").appendChild(tree);

I am exploring JavaScript and HTML, trying to add multiple hyperlinks within a div named 'hyperlinks' by hard-coding it. The links are extracted from an array of URLs called 'urlList'.

However, the current issue I face is that only one hyperlink is displayed with all the URLs as text, and the URL attached to the link corresponds to the last URL in the urlList array. Any guidance on rectifying this is appreciated. Thank you.

Answer №1

Issue

Repetitively configuring the same object every time

Resolution

Generate a new object for each iteration

for(let count = 0; count < urlList.length; count++) {
  const fragment = document.createDocumentFragment();
  const anchor = document.createElement('a');
  anchor.appendChild(document.createTextNode(urlList[count]));
  anchor.setAttribute("href", urlList[count])
  anchor.setAttribute("id", "link "+count)
  fragment.appendChild(anchor);
  document.getElementById("hyperlinks").appendChild(fragment);
}

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

External JavaScript files are also subject to the same origin policy

Suppose a website http://www.mysite.com contains an external JavaScript file added like this: <script src="http://www.yoursite.com/new.js"></script> Within the http://www.yoursite.com/new.js JavaScript file, there is an AJAX call to a script ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

When I avoid using a string ref, I encounter the error message "Error: Function components are not allowed to have string refs"

Recently, I created a new component const Projects = () => { const state ={ activeItemID: 1 } const CarouselRef = useRef(null); const NextSlide = () => { CarouselRef.current.style = "opacity: 0"; } return( <Co ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

How to use jquery and ajax to retrieve an array of data and show it on the screen

I am facing an issue with my ajax request. Actually, I am unsure of how to fetch multiple records. I attempted the following: $rqt = "SELECT a,b,c from table"; $res = mysql_query($rqt); while ($data = mysql_fetch_assoc($res)): $objet = $d ...

Trigger ng-change event for each dropdown selection made in AngularJS

Currently, I have a dropdown menu that allows users to select a report for generation. When a user picks a report from the dropdown, it generates and downloads the report for mobile viewing. By utilizing ng-change, the system only detects when a user wants ...

Retrieve the most recently added child from the Firebase cloud function

Seeking assistance in retrieving the most recently added child in a cloud function. Below is the code snippet I am using and I'm curious if there is a specific function or query I can utilize to achieve this task without having to iterate through each ...

Retrieving JSON data to create and showcase an HTML table

Can you help me figure out what's going wrong with my code? I have an HTML page with a table where I fetch data from the web in JSON format using JavaScript. The logic works perfectly when the fetch code is let to run on its own, but when I try to ex ...

I am experiencing some issues with React Router V4's functionality

I am currently developing a web application where I intend to showcase user details on the same page using routers when they are clicked. Below is my index.js file: window.React = React; render(<div> <Menu/><MainMenu/><App/>&l ...

Is it better to append content in JQuery rather than replacing it with .innerHTML?

Here is a function designed to retrieve older wallposts from a user, 16 at a time, and add each chunk of 16 to the end of the current list in the div called "sw1". The function works well, except when there is a wallpost containing a video or embedded obj ...

Changing a property of an object in Angular using a dynamic variable

It seems like I may be overlooking a crucial aspect of Angular rendering and assignment. I was under the impression that when a variable is updated within a controller's scope, any related areas would automatically be re-evaluated. However, this doesn ...

Striking a balance between innovation and backward compatibility in the realm of Web Design/Development

Creating websites is my passion, and I enjoy optimizing them for various platforms, devices, and browsers. However, lately, I've been feeling frustrated. I'm tired of facing limitations in implementing my creative ideas due to outdated technolog ...

What are the ideal scenarios for implementing React.Fragments?

Today I discovered React Fragments and their benefits. I learned that fragments are more efficient by reducing the number of tree nodes and improving cleanliness in the inspector. However, is there still a need to use div tags as containers in React compo ...

Sequencing numerous promises (managing callbacks)

I am encountering some challenges with promises when it comes to chaining multiple ones. I'm having difficulty distinguishing how to effectively utilize promises and their differences with callbacks. I've noticed that sometimes callbacks are trig ...

"Combining the power of Angularjs and the state

I've been delving into Redux, mainly in the context of using it with React. However, I use AngularJS. Is there a compelling advantage to implementing Redux instead of handling state within AngularJS scope and letting Angular manage the bindings? ...

Having trouble accessing jQuery function within WordPress

Why is there a ReferenceError: Error message that says "manualEntry is not defined," appearing while trying to use the code snippet below in a Wordpress environment? <a href="#" onclick="manualEntry()">hide</a> <script ...

Showing a pop-up on a click of a dynamically created table row, showcasing information specific to that row

I am facing a challenge with my dynamically generated table that is based on the JSON response from an AJAX call. What I am trying to achieve is to display additional data in a modal when a table row is clicked. This would be simple if the data was hard co ...

Quick method to populate an array with elements

I need to populate an array with a large number of objects. Currently, my approach looks like this: let useVertices = []; const len = this.indices.length; for(let i = 0; i < len; i++){ let index = this.indices[i]*3; useVertices.push(new THREE.Ve ...

Verify if the radio element is marked as selected in the AJAX reply

My ajax response contains two radio elements and I need to check if they are checked in the response. I've tried using the code below to check the radio status but it's not working: $('#input[type=radio]').each(function(){ alert($( ...

How to effectively manage errors in WCF using JavaScript?

Does anyone have instructions on using callback functions in a WCF Service that is accessible to Javascript? I am particularly interested in retrieving information from the FailureCallback to understand why my method is not working as expected. To clarify ...