Utilizing JSON for the setAttribute() method

While I've made progress on this issue, I've encountered numerous confusing methods. The goal is to utilize the key:value pairs in attr{} for the setAttribute() function without relying on any framework.

If anyone could provide a straightforward solution:

testDiv = document.getElementById("testDiv");


attr = {

    align:"center",
    title:"The Test Div"

};

//Is it possible to convert JSON to a string and then use it in setAttribute?

for(var x in attr) alert(x + " , " + attr[ x ] );

testDiv.setAttribute( x ,  attr[ x ]);

Answer №1

Looks like you're working with an object literal instead of JSON in your code. If I understand correctly, you're trying to set multiple attributes for a specific element. You can achieve this easily by creating a reusable function with a loop:

function setAttributes(element, newAttributes) {
   for (var attr in newAttributes)
     element.setAttribute(attr, newAttributes[attr]);
}

var targetElement = document.getElementById("targetElement");

setAttributes(targetElement, { color : "blue", type : "button" });

Answer №2

Forget about “JSON” (basically just a JavaScript object literal) and setting attributes, your issue lies within this chunk of code:

for(var x in attr) alert(x + " , " + attr[ x ] );

testDiv.setAttribute( x ,  attr[ x ]);

The problem arises because you are not using braces with the for loop, which means only the statement immediately following it gets executed. By adding braces, the corrected code would look like this:

for(var x in attr){
    alert(x + " , " + attr[x] );
}
testDiv.setAttribute( x ,  attr[x]);

The setAttribute method isn’t being called inside the loop — it's only called once at the end. What you probably want to do is...

for(var x in attr){
    alert(x + " , " + attr[x] );
    testDiv.setAttribute( x ,  attr[x]);
}

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

The curious behavior of JavaScript object fields in Chrome

Attempting to update the targetRow's field with a variable converted from a string to a number is resulting in strange output in Chrome's console: targetRow[fieldName] = Number(value); console.log(targetRow[fieldName]); // = ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

Executing a JavaScript function without passing arguments does not yield the desired result

Within my JS file, I encountered an issue when trying to call one function from another. Initially, I called the function with no arguments using only its name handleResponse. However, when attempting to add arguments by changing the function signature, I ...

Using jQuery to smoothly scroll to a specific class name

I am faced with an HTML code snippet that looks like this: <div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div> My intention is to use jQuery to scroll to the game number 456 as shown below. var contain ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...

I'm consistently encountering issues with my ajax call, does anyone have any suggestions on how to fix

Struggling to grasp JSON concepts with real-life examples. Sadly, every time I run my example code, it returns an error saying [Object object]. I've scoured StackOverflow for solutions but haven't had any luck in getting it to work. What should I ...

What methods does a webpage use to track views and determine when content has been seen?

I am interested in learning about the code and mechanism that detects when a specific section of a webpage has been viewed (purely for educational purposes). For instance, on websites like StackExchange it tracks when someone has thoroughly read the "abou ...

Do you know the method to make a Youtube iframe go fullscreen?

I am encountering an issue with developing an iframe where I am unable to make it go fullscreen from within the iframe. Fullscreen API works when both the iframe and hosting website are on the same domain, as well as triggering fullscreen from outside the ...

How can a loading indicator be displayed while retrieving data from the database using a prop in a tabulator?

Incorporating a tabulator component into my vue app, I have set up the Tabulator options data and columns to be passed via props like this: // parent component <template> <div> <Tabulator :table-data="materialsData" :ta ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

React with TypeScript - Troubleshooting TS Error when Iterating over List Item (LI) Elements

Iterating through a group of <li> elements to strip away a specific class, then applying the same class to a different <li>. See the snippet below: useEffect(() => { if (dnArrowIdx === undefined) { const allLi = Array.from(document. ...

Total number of requests made since the previous reset

I'm currently working on developing an API and I need to set up a route like api/v1/status in order to check the server status. This route should return a JSON response with the total number of requests made to the API since it became active. However, ...

What is the reason that when the allowfullscreen attribute of an iframe is set, it doesn't appear to be retained?

Within my code, I am configuring the allowfullscreen attribute for an iframe enclosed in SkyLight, which is a npm module designed for modal views in react.js <SkyLight dialogStyles={myBigGreenDialog} hideOnOverlayClicked ref="simpleDialog"> <if ...

What is the best approach for extracting functions from express routes for unit testing?

I have a JavaScript controller containing some exported routes. I am interested in accessing the functions used within these routes for unit testing purposes. While many blogs suggest creating actual HTTP requests to test express routes, I consider this t ...

What could be causing the undefined value of $routeParams?

I've encountered an issue while attempting to utilize a service for managing an http request: angular .module('app') .factory('stats', function($http){ return { getStats: function(path) { ...

What is the best way to eliminate the space between two paragraphs?

Check out my awesome image! I need some help with formatting HTML data into text. Can anyone advise me on how to eliminate the space between two paragraphs? func processGetDescriptionResponse(json: JSON) { let status = json.dictionaryObject!["statu ...

Utilizing a .ini file to assign variables to styles elements in Material-UI: A comprehensive guide

I need to dynamically set the background color of my app using a variable retrieved from a .ini file. I'm struggling with how to achieve this task. I am able to fetch the color in the login page from the .ini file, but I'm unsure of how to apply ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

Node.js encounters a conflict between route names and directory names

Can you use the same name for both a route and a directory in a Node.js project? For example: require("./test")(router); And inside the test.js file: app.get("/test", function(req, res) {}); Also, test is a directory in the same project. When attempti ...

Is dirPagination failing to display pagination links correctly?

I am currently attempting to implement server-side pagination in my application, but I am facing challenges as the paging option seems to be missing. I have been following this tutorial for guidance. Below is a snippet of my code: JavaScript: $scope.vm= ...