1

I don't know if this is possible or how to do it but what I want to do loop through some elements with a class, get the id and see if the value of the id is a key name in a JSON object. If it is, I want to get the corresponding value and pass it back to the elements HTML.

var options = {
    "test1": "something",
    "test2": "something else",
    "test3": "something amazing",
}

$('.myclass').each(function(i, val) {
    if(options.hasOwnProperty(val.id)) {
        $('#' + val.id).html(options.val);
    }
});

<p class="myclass" id="test1"></p>
<p class="myclass" id="test2"></p>
<p class="myclass" id="test3"></p>

The problem is with this line specifically options.val. I was thinking about a variable variable but don't know how to do that in javascript or looking for another way.

$('#' + val.id).html(options.val);

1 Answer 1

2

You can loop through the properties of your js object, get the property name,Check the similar element exists in the UI, If yes, read the value and set to the elements inner html using html method.

  for(var propertyName in options) {

    var e =$("#"+propertyName);
    if(e.length)
    {
        e.html(options[propertyName])
    } 

  }

Working sample here

Sign up to request clarification or add additional context in comments.

2 Comments

This was exactly what I was looking for. Will accept as soon as I can
@AdRock Thanks ! Glad i could 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.