Updating hrefs within an array using a JavaScript function

I specialize in creating web resumes and would like to include URLs for my projects and previous employers. I attempted to use a function for this purpose, but encountered an issue where only the first project was being updated with the URL from the last element in the projects array.

for (project in projects.projects) {
    document.getElementById("ptitle").href=projects.projects[project].url/  }

To view my code, please visit: http://bl.ocks.org/DariaAlekseeva/c58df25c4cded4d1a678

Thank you!

Answer №1

Remember, each element on a page must have a unique ID. Using document.getElementById() will only target the first element with that specific ID.

In the code snippet you've shared, it keeps updating the same element's href repeatedly within a loop over an array of objects.

If you're handling multiple elements that share similar characteristics, consider utilizing classes.

Take a look at this example assuming your HTML classes align with the object array and are ordered as expected. It should help guide you in the right direction.

Check out the Demo

HTML

<ul>
  <li class="myClass"></li>
  <li class="myClass"></li>
  <li class="myClass"></li>
  <li class="myClass"></li>
  <li class="myClass"></li>
  <li class="myClass"></li>
</ul>

JS (using jQuery because it seems you're familiar with it already)

var projects = { 'projects' : 
  [
    {'url' : 'zero'},
    {'url' : 'one'},
    {'url' : 'two'},
    {'url' : 'three'},
    {'url' : 'four'},
    {'url' : 'five'}
  ]
};
    
$('.myClass').each(function (index) {
  $(this).text(projects.projects[index].url);
});

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

``Unresolved issue: Sending emails using Sendgrid and Firebase not working in production through Netlify

For a simple contact form, I am utilizing Nuxt, Sendgrid, and Firebase. Netlify is being used for hosting the project. The contact form works perfectly fine locally and sends emails without any issues. However, once I push the project to Netlify, the email ...

Passing a variable between functions in JavaScript: Tips and tricks

let chart; let data = new Array(); function handleClick() { data = document.getElementById('graph:hi').value; alert(data); } let chartData = new Array(66, 15, 2.5, 21.9, 25.2, 23.0, 22.6, 21.2, 19.3, 16.6, 14.8); alert(chartData); jQuery ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Struggles with establishing a connection to the Gmail API

I am facing some challenges connecting to the Gmail API. Despite completing the setup process and obtaining a valid token on OAuth 2.0 Playground, I encounter errors when trying to send mail from a form on my Node.js / Express / Nodemailer server. The term ...

What are the various methods for increasing a pointer in C, and how do they differ from each other?

Currently, I am learning C and was faced with the challenge of incrementing a pointer in a specific scenario. Let's assume we have this setup: int A[] = {111, 222, 333}; int *q = A;. My goal is to increment the pointer q from the zero-index of array A ...

The images in my gallery refuse to hover or respond to my clicks

Ever since integrating this cropping effect (http://jsfiddle.net/BPEhD/2/) to my gallery images, I've encountered an issue - the hover state is missing and I can't click on the images either. Although the pointer cursor appears when I hover over ...

What causes the Vue.http configuration for vue-resource to be disregarded?

I am currently utilizing Vue.js 2.3.3, Vue Resource 1.3.3, and Vue Router 2.5.3 in my project while trying to configure Vue-Auth. Unfortunately, I keep encountering a console error message that reads auth.js?b7de:487 Error (@websanova/vue-auth): vue-resour ...

Analyzing the HTTP status codes of various websites

This particular element is designed to fetch and display the HTTP status code for various websites using data from a file called data.json. Currently, all sites are shown as "Live" even though the second site does not exist and should ideally display statu ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

Issue with accessing Jade variable from an array

My challenge is in passing an array to the jade document and accessing the values using a variable to simplify the markup. The example below outlines my issue. While I understand that the jade syntax for arrays can be tricky, such as "arr.[0]", I seem to ...

The addClass method in jQuery is failing to append the specified class to the element

I'm currently working on a registration form that includes selecting your gender: My goal is to have the male icon turn blue when clicked, and the female icon turn pink. The color change currently works when hovering, but not when clicked. Here is th ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Different from Window.Print()

I am looking to implement a print button that will trigger the printing of the entire webpage when clicked. I have been attempting to achieve this using Window.print() in JavaScript, but I encountered an issue where the link stops working if the print bu ...

Mastering the ins and outs of ngStorage in AngularJS

Imagine a web page featuring a form that allows users to input multiple entries before submitting. As each entry is added, a summary of the data entered is displayed in a table at the top. Once all entries are completed, the user can then proceed to submit ...

Simplify an array in Javascript

I have a collection of objects structured in the following way: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] My goal is to flatte ...

Fetching the second item within an object using JavaScript

I am trying to retrieve the data from the last month of an API, but I want to avoid hard-coding the date like this: const data = [data.data['Monthly Time Series']['2021-11-30']]. I need a way to dynamically access the 2nd object without ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...