Generating innerHTML and retrieving attributes simultaneously from a single Div element

Looking for a way to extract an attribute from a div and use it to create a link within the same div with the attribute included in the src.

Currently, my code only picks up the first attribute, resulting in all links being the same.

I am still a beginner in JS, so please excuse me if the solution is obvious

var srpVin = document.querySelectorAll('span[data-cg-vin]')[0].getAttribute("data-cg-vin");

 var srpVsaBtn = document.getElementsByClassName('carBannerWrapper');
for (var i = 0; i < srpVsaBtn.length; i++) {
    srpVsaBtn[i].innerHTML += '<a href="https://myurl.com/?vin='+srpVin+'&dealer_id=28987" target=_deal>Click here - '+srpVin+'</a>';
}
<div class="carBannerWrapper"><div><span data-cg-vin="1FMCU9G66MUA11123" data-cg-price="34399"></span></div></div>
<div class="carBannerWrapper"><div><span data-cg-vin="MAJ3S2GE7LC386456" data-cg-price="34399"></span></div></div>
<div class="carBannerWrapper"><div><span data-cg-vin="11FMCU9H67LUC59789" data-cg-price="34399"></span></div></div>

Answer №1

To start, retrieve all the spans using the querySelectorAll method. This will give you a NodeList object, which can be iterated over using the forEach function.

Within the loop, each <span> element is accessible. This allows you to manipulate the properties of these elements. Utilize the dataset property when working with data attributes, as it holds the values of each attribute.

Instead of using innerHTML, opt for document.createElement to create a new <a> tag. By creating an anchor tag as an object, you can manually set the href property of the anchor based on the dataset value.

Use the append() method on the span to add the anchor as a child of the current span in the loop.

Note: It is important to be aware that _deal is not a valid value for the target attribute. Refer to the list of acceptable values here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target

// Retrieve all spans with the data-cg-vin attribute.
const srpVin = document.querySelectorAll('span[data-cg-vin]');

// Iterate over each span.
srpVin.forEach(span => {
  // Obtain the value of the data-cg-vin attribute for the current span.
  const cgVin = span.dataset.cgVin;

  // Create a new <a> tag.
  const anchor = document.createElement('a');

  // Set the href, target, and textContent based on the data attribute value.
  anchor.href = `?vin=${cgVin}&dealer_id=28987`;
  anchor.target = '_blank';
  anchor.textContent = `Click here - ${cgVin}`;

  // Append the anchor to the span.
  span.append(anchor);
});
<div class="carBannerWrapper"><div><span data-cg-vin="1FMCU9G66MUA11123" data-cg-price="34399"></span></div></div>
<div class="carBannerWrapper"><div><span data-cg-vin="MAJ3S2GE7LC386456" data-cg-price="34399"></span></div></div>
<div class="carBannerWrapper"><div><span data-cg-vin="11FMCU9H67LUC59789" data-cg-price="34399"></span></div></div>

Answer №2

Utilize the forEach method to loop through each element.

var srpVsaBtn = Array.from(document.querySelectorAll('.carBannerWrapper'));

srpVsaBtn.forEach(btn => {
  const link = btn.querySelector('span').dataset.cgVin;
  btn.innerHTML = '<a href="https://myurl.com/?vin='+link+'&dealer_id=28987" target=_deal>Click here - '+link+'</a>';
})
<div class="carBannerWrapper"><div><span data-cg-vin="1FMCU9G66MUA11123" data-cg-price="34399"></span></div></div>
<div class="carBannerWrapper"><div><span data-cg-vin="MAJ3S2GE7LC386456" data-cg-price="34399"></span></div></div>
<div class="carBannerWrapper"><div><span data-cg-vin="11FMCU9H67LUC59789" data-cg-price="34399"></span></div></div>

Answer №3

Are you in search of a solution involving forEach to loop through a nodelist? Check out the code snippet below:

var srpVin = document.querySelectorAll('span[data-cg-vin]').forEach(function(elem,idx) {
  elem.getAttribute("data-cg-vin");
});

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

Alert! Server node encountered an issue while handling the response: process.nextTick(function(){throw err;});

Currently, I am working on a simple application to familiarize myself with Mongo, Express, and Node. An issue arises when I attempt to utilize res.json(docs) in the success conditional during the GET request, generating an error process.nextTick(function( ...

Seeking the perfect message to display upon clicking an object with Protractor

Currently, I am using Protractor 5.1.1 along with Chromedriver 2.27. My goal is to make the script wait until the message "Scheduling complete" appears after clicking on the schedule button. Despite trying various codes (including the commented out code), ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Tips on how to bring in .js that has brought in .json from an html file

English is not my first language, and I struggle with it, but I did my best. I am attempting to include a js file that imports json from an html .js import menus from '../json/menus.json'; (function () { function parseMenu(ul, menu) { fo ...

Is dynamic data supported by Next.js SSG?

I'm currently developing a web application with Next.js and I need clarification on how Static generated sites work. My project is a blog that necessitates a unique path for each blog entry in the database. If I were to statically generate my web appl ...

Learn the steps to retrieve a user's profile picture using the Microsoft Graph API and showcase it in a React application

I'm currently working on accessing the user's profile picture through Microsoft's Graph API. The code snippet below demonstrates how I am trying to obtain the profile image: export async function fetchProfilePhoto() { const accessToken = a ...

Browser freezes unexpectedly every 10-15 minutes

I have an application that displays 10 charts using dygraphs to monitor data. The charts are updated by sending ajax requests to 4 different servlets every 5 seconds. However, after approximately 10-15 minutes, my browser crashes with the "aw! snap" messag ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

What is the best way to hide only the rows in a table when it is clicked using JavaScript?

Is there a way to hide rows in these tables by clicking on the table head? I'm currently using bootstrap 5 so JQuery is not an option. <table class="table table-info table-bordered"> <thead id="tablea"> ...

I struggle with generating a transition effect in the input box through label transformation

Why is the input box not using the specified CSS styles for the input and label tags? The transform property doesn't seem to be working as expected. I've highlighted the areas where I'm facing issues with bold text, and I've included bo ...

What is the best way to ensure a jQuery function runs on duplicated elements?

I have been attempting to construct a webpage featuring cascading dropdowns using jQuery. The goal is to generate a duplicate set of dropdowns when the last dropdown in the current set is altered. I aim for this process to repeat up to 10 times, but I cons ...

Unable to retrieve Java variable in JavaScript

Seeking guidance on how to retrieve Json data stored in a Java variable using JavaScript. Instead of accessing the data, the html source is displayed. Java: Gson gson = new Gson(); String json = gson.toJson(obj); request.setAttribute("gsonData", gson) ...

React is giving me trouble as I try to map my tables. I am struggling to figure out how to do this

I have two .CSV files: "1.csv" and "2.csv". I need to display the data from each file in a table using the BootstrapTable component. My async functions, GetData(file) and FetchCSV(file), are working fine and providing the necessary array of objects for the ...

Getting the id of a row from a v-data-table in VueJs

I am currently facing an issue with retrieving the id of a specific field from each row. I require this id as a parameter for a function that will be utilized in an action button to delete the row. Here is how my table template appears: <template ...

Utilizing AngularJS to create an auto complete feature integrated with a SQL Server database

I have a SQL database table with columns as follows: Row1 Row2 Row3 Id Country 1 1a 1b 34 Europe 2 2a 2b 45 US 3 3a 4d 5g Australia I am currently working on implementing an autocomplete feature ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

"Unusual HTML and jQuery quirk causing a perplexing issue: a function that keeps looping inexp

A unique code written in javascript using jQuery allows users to create a "box" on a website with each click of a button, triggering an alert message upon clicking the box. The process is as follows: 1) Clicking the "Add (#addBox)" button appends a new li ...

Disconnect occurred during execution of Node.js "hello world" on a Windows 7 operating system

Issue Resolved: Oh no! jimw gets 10000 points for the solution! I've decided to delve into a hobby project using Node.js. Here's where I started: Downloaded and installed Node version 0.6.14 Copied and pasted the classic "hello world" program ...

Using Node JS as both an HTTP server and a TCP socket client simultaneously

Currently, I am developing a Node.js application to act as an HTTP server communicating with a TCP socket server. The code snippet for this setup is displayed below: var http = require('http'); var net = require('net'); var url = requi ...

Issue encountered while attempting to send a direct message to a user that has been mentioned

Attempting to create a reminder command in discord.js with two arguments: the message and the mentioned user to remind but encountering an error. Code snippet: client.on('message', (message) => { const { content, guild, channel, author } = m ...