Retrieving the JSON value from a data attribute and then locating the corresponding JSON key in a designated element within the DOM

I have an HTML element that contains a data attribute:

<a href="#" data-trigger="{ "rem": "albatros", "ap":1 }'">Remove</a>
<div data-container>
    <p>lorem ipsum<p>
    <p data-rem></p>
</div>

1.

Sometimes (but not always) a value is sent in the data-trigger attribute:

I am trying to select all elements that have the attribute data-trigger:

document.querySelectorAll(['data-trigger']).forEach(function (trigger, index) {

Then, for each of these trigger elements, I aim to retrieve the DOM and JSON value and parse it:

dom = trigger;   
value = JSON.parse(trigger.getAttribute('data-trigger'));

Although I successfully retrieve the DOM reference, I always end up with a null value.

Does using getAttribute trigger a reevaluation in the DOM?

  1. Iterating through the data-container, I search for elements that contain attributes corresponding to one of the keys found in the JSON.parse result. I then proceed to set the value of these elements to the value of the key.

For instance:

<p data-rem>albatros</p>

Answer №1

The current roadblock for your script is the incorrect selector inside querySelectorAll().

Make sure it is '[data-trigger]', not ['data-trigger'].

Once you correct this, you will successfully retrieve all elements with a data-trigger attribute. However, keep in mind that the string in the data-trigger attribute as it stands will not be parsed as a JavaScript object. To fix this, replace quotes with double quotes and vice versa to create a valid JSON string that can be parsed like this:

<a href="#" data-trigger='{"rem": "albatros"}'>Remove</a>
JSON.parse(elem.getAttribute('data-trigger')) // where elem refers to the DOM element above

Although the purpose of your script is not entirely clear, assuming you are looking to find DOM elements with 'data-'+foundKey equal to foundVal, you can use the following selector:

document.querySelectorAll('[data-'+foundKey+'="'+foundVal+'"]').forEach(function(el, i){
  console.log(el, i);
})

However, based on your current elements, this selector will not return any results because there is no element like:

<x data-rem="albatros"></x>

Here's an example that demonstrates the concept applied to your code:

document.querySelectorAll('[data-trigger]').forEach(function (trigger, index) {
  const triggerProp = JSON.parse(trigger.getAttribute('data-trigger')),
        foundKey = Object.keys(triggerProp)[0],
        foundVal = triggerProp[Object.keys(triggerProp)[0]],
        targets = document.querySelectorAll('[data-'+foundKey+']').forEach(function(target, index) {
    console.log(target, 'key:'+foundKey, 'val:'+target.getAttribute('data-'+foundKey));
  });
})
<a href="#" data-trigger='{"rem": "albatros"}'>Remove</a>
<div data-container>
    <p>lorem ipsum<p>
    <p data-rem="test"></p>
</div>

Keep in mind that this example works because the data-trigger value is valid JSON. To prevent failure, consider adding a try/catch block to test if the value is valid JSON before parsing. Alternatively, you can use a library that handles relaxed JSON parsing.

Answer №2

This JSON String is not considered valid.

<a href="#" data-trigger="{'rem': 'albatros'}">Remove</a>

If you want a valid JSON String, try this:

<a href="#" data-trigger='{"rem": "albatros"}'>Remove</a> <!-- Remember to use double quotes for JSON -->

Next:

document.querySelectorAll("[data-trigger]").forEach(function (trigger, index) {
  var val = JSON.parse(trigger.getAttribute('data-trigger'));
  for( key in val){ //Loop through (JSON-)Object
  setInnerElements(val[key], key);
  }
  
});

function setInnerElements(val,key){

document.querySelectorAll("[data-container] > [data-"+ key +"]").forEach(function (el, index) {
  el.innerHTML = val;
  })
}
<a href="#" data-trigger='{"rem": "albatros", "foo":"test1", "bar":"test2"}'>Remove</a>
<div data-container>
<p>lorem ipsum<p>
<p data-rem></p>
<p>lorem ipsum<p>
<p data-foo></p>
<p>lorem ipsum<p>
<p data-bar></p>
</div>

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

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

remove leading spaces in JavaScript after retrieving data from database

Hey there, I need help with trimming the leading spaces using JavaScript when the value is fetched from a database. I am using JSP tags to retrieve the value and load it into an input field. The issue I'm facing is that if there are any spaces at the ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

Don't give up on the entire task just because one promise was rejected

To handle multiple promises in redux saga, you can use the all function (equivalent to Promise.all): yield all( users.map((user) => call(signUser, user)), ); function* signUser() { yield call(someApi); yield put(someSuccessAction); } An issue ...

"Make a phone call following the completion of an HTTP

Upon receiving and storing data, I am looking to execute a function but the code I currently have is not producing the desired result. Could someone provide some insight into what I might be doing incorrectly? Here's my current code snippet: $h ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

Efficiently update a multi-step form using Ajax and jQuery by adding new content without needing to reload the

Is it possible to create a multistep form on a single page without reloading the div with content from a PHP file, but instead appending it below? Here is my current progress: $(document).on('submit', '#reg-form', function(){ var ln = ...

Error: When attempting to send a message in a different channel, an undefined property 'send' is encountered causing a TypeError

I'm utterly stumped as to why I keep encountering this issue, so perhaps someone here can shed some light on it. The error message reads: TypeError: Cannot read property 'send' of undefined Here is the snippet of code in question: client.o ...

Creating dynamic values in data-tables using Vuetify

As I work with JSON data, my current task involves formatting it using Vuetify's Data Tables. The official documentation provides guidance on defining table headers as shown below: import data from './data.json' export default { data ...

Is there a way to keep my fixed button at a consistent size while zooming on mobile devices?

There are no definitive answers to the questions regarding this issue. Some suggest stopping zoom altogether, while others recommend setting the width, which may not always solve the problem. I am working on a web application designed for mobile use with ...

What is the correct way to encode an HTML string in JavaScript?

I have identified a XSS Scripting vulnerability in my code and I want to prevent it. To do so, I am utilizing a Jquery Encoder for protection against XSS Scripting attacks. Below is the JavaScript code snippet: function test(response) { $('#test ...

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

The JSONObject encountered an exception as it could not find a value for the

Encountering the same old exception while developing my android application The 'message' key is missing in the JSON data I'm certain that the JSONObject I possess holds the desired information: View and analyze my JSON Object for bette ...

What is the process for loading a font file in Vue.js and webpack?

I've done a lot of research, but I couldn't find any links that show me exactly how to add fonts in VueJS. This is the method I'm using to import the font in my LESS file: @font-face { font-family: "Questrial"; src: url("../../fonts/Que ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

Steps to create an iframe that opens in a new window

I'm facing an issue with the iframe sourced from flickr. My website includes an embedded flickr iframe to showcase a gallery without the hassle of creating a slider, resizing images, and extracting thumbnails. Given that this site belongs to a frien ...

Showcasing articles in an XML feed according to specific keywords found in the headline

I'm currently working on designing a website for a client and I want to minimize my involvement in its maintenance. I am considering using RSS feeds to automate the process by having content posted on Blogger and then feeding it to the site. However, ...

When receiving a GET response after a server crash

Question: I am sending a Get request through Ajax every second and waiting for a response from the server. However, if my application crashes and I keep sending requests every second, I only receive a server timeout error (HTTP status code 502) with no oth ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...