I have this piece of code to replace current text inside an array of html divs with values coming from a JSON file:

    $.each($('.something'), function(){
        }else if($(this).text()=="2"){

I'd like to make it "dynamic": if I'd have 100 values, I don't want to copy/paste it 100 times.

Maybe it would be better creating an array "CameraTypeLabel" in the JSON string ?

EDIT: Fixed the selector, it was a typo.



jQuery's .html() method can take a callback function - it'll be called for every element in the collection - and will use the returned value to set the element's html.

You can use bracket notation to access the key in your jsondata, so that you can dynamically get to the key you want with the string in the brackets:

$('.something').html(function () {
    return jsondata[ 'CameraTypeLabel' + $.text(this) ];

Note: $.text(this) is the same as $(this).text(), just a bit faster; it doesn't create a new jQuery object at every step in the loop.

If all you want to do is update the text, you can pass a function to .text() itself:

$('.something').text(function (i, oldText) {
    return jsondata[ 'CameraTypeLabel' + oldText ];

This answer assumes that the elements you want to replace are in the same order as the json content is. Ex.:

<div class="something">0</div>
    <div class="irrelevant shitty div that won't be selected"></div>
<div class="something">1</div>
<div class="something">2</div>

If so, no .text() check is needed and you can just use the index.

   $('.something').each(function(i) {

        var arrayOfDivs = ["something0", "something1", "something2"], //array of html divs
            jsondata = "whatevaaa is coming in from json"; //value coming from json

            var index = arrayOfDivs.indexOf("something" + [i]); //find element to be replaced

            if (index !== -1) { //check to see if element was found
                arrayOfDivs[index] = jsondata; // replace the current text of matched element, in arrayOfDivs, with what comes in from json
                //You can also replace the html in the div from here:



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.