Discover the solution to this JavaScript function

When I make the call to this particular function, the following code is executed:

   el=DOM.create({tag:"div",css:{backgroundColor:"#000000",color:"green"},html:"abc"});
   $("#fb_dv").append(el);

This is where my function resides:

DOM={
    create:function(data){
        if(data.tag){
            d=document;
            doc=d.createElement(data.tag);
            for(var v in data){
                 if(v=="css"){
                     for(key in data[v]){
                        prop=doc.style;
                        prop.key=data[v][key]
                     }
                 }
                 if(v=="html"){
                     doc.innerHTML=data[v]
                 }
            }

            return doc;
        }
    }
}

The issue at hand is that it seems this function isn't correctly applying the specified css properties.

Answer №1

The issue lies within the for loop responsible for setting the styles. Utilizing the square bracket syntax is crucial in order to correctly assign the property:

for(key in data[v]){
    prop = doc.style;
    //prop.key = data[v][key]... modify this to:
    prop[key] = data[v][key];
}

Check out a working example here.

On another note, make sure to include all necessary var statements to avoid variables leaking into the global scope, and don't forget those semi-colons.

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

Having trouble grasping this error related to the module or type

Currently, I am experimenting with the Aeson JSON library in Haskell. My current goal is to utilize the "decode" function to interpret a JSON dump. import Data.Aeson import Data.ByteString as BS import Control.Applicative main :: IO () main = print $ dec ...

Protecting String in PHP to Utilize in JavaScript

When I receive code through AJAX, I handle it as shown below: $verifiedSubject = addslashes(htmlentities($_REQUEST['subject'])); $verifiedBody = addslashes(htmlentities($_REQUEST['body'])); $verifiedAttachment1 = addslashes(htmlentitie ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

The link in the Ajax open() method

I'm experiencing some trouble with my first Ajax program and I could really use some help in identifying the issue in the code. The debugger is throwing an error that reads, "XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-C ...

Proceed once all .load() functions have been completed

I am encountering an issue with an asynchronous JavaScript function. I currently have a function that is inserting elements one by one, which is functioning correctly. However, my goal is to proceed only after all the .load() functions have completed. The ...

Manipulating the data stored in a JSON file with MFC

While I can successfully parse JSON files in MFC, I am encountering difficulties when it comes to modifying the values. Is there a simpler method for adding new values without having to convert them to native file types, make changes, and then convert back ...

The ObjectSpaceNormalMap feature is not functioning properly when used in conjunction with MeshNormal

I'm having trouble getting the MeshNormalMaterial to stay aligned with the object instead of the camera. I set .normalMapType = THREE.ObjectSpaceNormalMap, but it doesn't seem to be working as expected. Is there something crucial that I might b ...

Node.js is not accurately setting the content length. How can I resolve this issue?

I could use some assistance. Even though I have set the content-length on the response object, it doesn't seem to be working. Have I done something incorrectly? res.set({ 'Content-Type': res._data.ContentType, 'Content-Length' ...

using a different path variable within an href attribute

<a id="m1" class="audio {autoPlay:false, addGradientOverlay:true}" href="MusicFolder/" + document.getElementById("DropDownList1").value + "/" + document.getElementById("DropDownList2").value>document.getElementById("DropDownList2").value</a> ...

Connecting two tables in an express API

Currently, I am in the process of developing an API using Express.js. At this stage, my initial tests are functioning correctly. My goal now is to retrieve values from two separate tables. For example, consider the following 2 tables: Table_A Id: 1, Name: ...

Receiving a 500 Internal Server Error while performing an AJAX POST to a web API using Json

I'm currently attempting to establish a connection to a web API from the client side using AJAX jQuery with the POST method. Here is a snippet of my code: <script type="text/javascript"> $(document).ready(function (){ $("#btn392").click(f ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

Transfer an array from XML to PHP into JavaScript in order to deactivate specific dates within a datepicker using the beforeShowDay function

My process involves reaching out to another website through a GET request and receiving XML data for interpretation. Here is how I make the contact: $v= file_get_contents( "https://www.v.com/fechasexcursion.php? agent=M&password=s&fec ...

The If-then condition is not functioning properly within the JSON Schema

Here is the JSON schema provided: { "$schema": "http://json-schema.org/draft-07/schema#", "type": "array", "items": [ { "type": "object", "properties": { ...

Value auto-populated from associated model

Currently, I have a situation where I have a table for zip codes and another table for persons. The goal is to automatically populate the city field in the person's table based on the zip code entered. It seems like this functionality may not be achie ...

Troubleshooting issue with C# Ajax success response not triggering alert

I am facing an issue where the alert box for success does not show even though the code successfully inserts contact details using ajax and C#. Strangely, when I debug through the JavaScript debugger in Chrome, the alert pops up as expected. Here is the co ...

JQuery Ajax: Issue with updating Total Likes for posts when Like button is clicked

There are two JQuery Ajax calls in this scenario. The first call retrieves user messages from MySQL, along with the number of likes for each message and a button for users to like the message. This initial request is functioning correctly. The second Ajax ...

``Is there a way to retrieve the file path from an input field without having to submit the form

Currently, I am looking for a way to allow the user to select a file and then store the path location in a JavaScript string. After validation, I plan to make an AJAX call to the server using PHP to upload the file without submitting the form directly. Thi ...

Retrieve Cryptsy Fee using timmolter's XChange tool

Looking for assistance with retrieving the market fee from an obscure API. Any ideas? Here is what I have tried: system.out.println("\nCalculateFees:\n" + ((CryptsyTradeServiceRaw) TradeService).calculateCryptsyFees(CryptsyOrder ...