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

MongoDB update operation is incomplete

My model includes fields such as "id," "liked," "likedBy," and "matched." I am updating my database to add an id based on hypothetical likes; it stores the target's id in the current user's liked field and the current user's id in the target ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

Using Vuex: Delay dispatch of action until websocket response received

Let's look at the given scenario and premises: To populate a chat queue in real time, it is necessary to establish a connection to a websocket, send a message, and then store the data in a websocket store. This store will handle all the websocket sta ...

Unable to navigate beyond the boundaries of an app

I am currently facing an issue with my authentication service where it redirects to the identity server in case of certain errors. I attempted to achieve this using window.location.href = environment.authCodeFlowIssuer;, however, an error occurred: Ref ...

What's the reason for the mousewheel functioning in Chrome but not in Firefox?

I am currently using CSS to enable scrolling up and down a popup page with just the mousewheel, but I'm facing an issue with it not working in FireFox. Surprisingly, it works fine in Chrome with the use of overflow-x:hidden; and overflow-y:auto; prope ...

Access the current page's URL using JavaScript

I have a unique URL structure that looks like this: index.html#page:page.php As I am loading my pages dynamically using AJAX, I want to create hotlinks to load specific pages. Currently, I am using the following function: function getdata(file){ $ ...

The function req.isAuthenticated() always returns false and never evaluates to true

My goal is to create user authentication using the following code: userRouter.post("/login", passport.authenticate("local", { session: false }), (req, res) => { if (req.isAuthenticated()) { const { _id, username } = req.user; const t ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Creating Multiple Fieldsets in a Drupal 8 Content Type

I have successfully created a group using a fieldset in the "manage form display" section. However, I am looking to replicate this group multiple times similar to what field collection can do. I prefer not to use field collection as it does not generate JS ...

php code to paginate mysql results

Imagine I have 50 rows in my database. How can I retrieve MySQL results in pages, displaying 5 results on each page and showcasing the pages as follows: [1], 2, 3, 4...10? For example, if it's on page 5, show 3, 4, [5], 6, 7...10 without refreshing al ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...

When accessing req.user in code not within a router's get or post method

Is there a way for me to access the data in the User schema outside of a post or get request? I am asking this because I would like to use this information elsewhere. The user schema is defined as follows: const mongoose = require('mongoose'); c ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

The Nuxt.js landing page is having trouble loading, but all other components are functioning perfectly

I successfully created a blog using Nuxtjs and everything was working perfectly in development mode. However, when I deployed the application to my cPanel server, the landing page (index.vue) at showed an error message saying This page could not be found ...

When you attempt to "add website to homescreen" on an iPhone, Ajax malfunctions

I have a unique website feature that utilizes ajax to dynamically load content when the user interacts with certain buttons. Everything functions smoothly up until a user tries to access the website through the "add to homescreen" option on mobile Safari a ...

I'm having trouble installing puppeteer

I tried running the command npm i --save-dev puppeteer to set up puppeteer for e2e testing. Unfortunately, an error occurred during installation: C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer > <a href="/cd ...

Using Angular to parse intricate JSON data

Need help parsing an http request in the following format: [ { "id": 1, "date": "2022-01-13T00:00:00.000+00:00", "time": "2022-01-13T21:21:21.000+00:00", "office&quo ...

Failed Attempt to Execute React Native Application using Command Prompt (iOS)

I'm currently working through the React Native tutorial found on their official website. During my project building process, I utilized the following command: react-native run-ios An error was encountered: Found Xcode project TestProject.xcodeproj ...