1

Say I have an element like :

var myElem='<div class="oldClass" style="color:green;" id="oldId"><span>This DIV has some 
innerHTML as well</span></div>'

And a JSON like:

var myJson = {
    "class": "myClass",
    "id": "myId",
    "style": "border: 1px solid black; color: red; font-size:20px;"
};

Now I need to update myElem with data in JSON.

What I tried is:

for(var key in myJson){
    var attrName = key;
    var attrValue = myJson[key];
    console.log('attrName ', attrName);
    console.log('attrValue ', attrValue);
    $(myElem).removeAttr(attrName);
    $(myElem).attr(attrName, attrValue);
}

My expectation from this code:

myElem = '<div class="myClass" style="border: 1px solid black; color: red; font-size:20px;" id="myId"><span>This DIV has some innerHTML as well</span></div>'

However, this is not working.myElem remains what it was initially.
myElem and myJson both are dynamic and not static
Can anyone please tell what am I doing wrong? (I know I'm doing something wrong but I'm unable to find it)!

2 Answers 2

2

You can pass the whole myJson object to attr and don't have to use a loop:

var myElem = '<div class="myClass" style="border: 1px solid black; color: red; font-size:20px;" id="myId"><span>This DIV has some innerHTML as well</span></div>';
var myJson = {
    "class": "myClass",
    "id": "myId",
    "style": "border: 1px solid black; color: red; font-size:20px;"
};

var elem = $(myElem).attr(myJson);

But if you want, it's even possible in a loop. I don't know why you want to, but it's possible. Just define your element outside the loop and here you go:

var elem = $(myElem);

for( var key in myJson ) {
    if( myJson.hasOwnProperty(key) ) {
        elem.attr(key, myJson[key]);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your quick response, i tried the first part which did not worked for me. I'm going to try the second one now and will let you know if it works for me. Thanks again.
I checked your fiddle and it works as expected. I tried both of your ways but none of them worked for me. I doubt there is something else in my code causing trouble but please have a look at this image. i.imgur.com/CF2exwo.png. These are console results of your second method.
It shows no error however the element is same as it was before. Note that "width" in JSON is not reflecting in FINALELEM.
As expected, there was something else causing problem in my code. Also, your code helped me in making my code better, so thanks a lot.
2

Problem

You're not editing the myElem but the temporary jquery instances of it.

Explication

In every iteration in your for loop you're creating a new instance of jquery object $(myElem) and when the .attr() and .removeAttr() execute they will change the attributes inside this new instance and every change will be overridden in the next iteration of the loop because it will create a new instance, so you are not editing myElem variable but the temporary jquery object instances of it.

jQuery Solution

If you want to edit the attribute of object using jquery function attr() you have two choices :

  1. Using the for loop : create a jquery object and let the function change the attributes, it will works fine check example bellow :

    var myElemJQueryInstance = $(myElem);
    
    for(var key in myJson){
        myElemJQueryInstance.attr(key, myJson[key]);
    }
    
    /*
    NOTE : Your code will be more clear/efficient if you use just function .attr()
             (no need for removeAttr()) because it will override the old value in the
             attribute if is exist.
    */
    
  2. By passing JavaScript object : You could pass a plain JavaScript object. Each key-value pair in the object adds or modifies an attribute (in your case the object is myJson) :

    $(myElem).attr(myJson);
    

JavaScript Solution

You could achieve that using pure js by the method setAttribute() :

for(var key in myJson){
    myElem = myElem.setAttribute(key, myJson[key]);
}

Hope this helps.


var myElem = '<div class="oldClass" style="color:green;" id="oldId"><span>This DIV has some innerHTML as well</span></div>'

var myJson = {
  "class": "myClass",
  "id": "myId",
  "style": "border: 1px solid black; color: red; font-size:20px;"
};

var myElemJQueryInstance = $(myElem);

for(var key in myJson){
  myElemJQueryInstance.attr(key, myJson[key]);
}

$('body').append(myElemJQueryInstance);
$('body').append(myElem);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2 Comments

There is no need for removeAttribute. And always use hasOwnProperty in object loops. And why do you cast every loop, a jQuery object into a jQuery object again? myElem = $(myElem) It's slow an aweful.
Thanks for help, you made me realize that i'm not actually appending the element created. Your code helped me but i'm choosing other answer as accepted one because its closer to what i needed. I really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.