Search code examples
jqueryappendto

jQuery appendTo with attributes from JSON


$.each(tools, function (i, tool) {
    $("<img>", tool).appendTo($toolbar);
});

//define toolset (JSON, e.g. from database)...
var tools = [{
    "data-id": 1,
    alt: "sun",
    title: "sun",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png",
    "data-description": "sun in photo"
}, {
    "data-id": 2,
    alt: "snow",
    title: "snow",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Thermometer_Snowflake.png",
    "data-description": "snow in photo"
}, {
    "data-id": 3,
    alt: "cloud",
    title: "cloud",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Overcast.png",
    "data-description": "cloud in photo"
}, {
    "data-id": 4,
    alt: "rain",
    title: "rain",
    src: "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Night_Rain.png",
    "data-description": "rain in photo"
}];

I am looking at some jQuery that I am seeing for the first time. I see that I believe what happens is for each tool and img tag is created with the appropriate attributes described in the JSON. If that is so I think that is very neat and I am wondering where might this technique be described in more detail perhaps in the manual or API documentation?

Thanks in advance...


Solution

  • the code:

    $.each(tools, function (i, tool) {
        $("<img>", tool).appendTo($toolbar);
    })
    

    let's part it in blocks:


    $.each(tools, function (i, tool) { }); - jQuery each

    this is the same as:

    for(i = 0; i < tools.length; i++) {
        var tool = tools[i];
    }
    

    $("<img>", tool) - jQuery element creator

    this is the same as having:

    $("<img data-id='' src='' alt='' title='' data-description=''>");
    

    and fill up with each set of parameters, for example, the first tool (the sun) would be:

    $("<img data-id='1' src='http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png' alt='sun' title='sun' data-description='sun in photo'>");
    

    which is the same as:

    $("<img>").attr({
        "data-id": 1,
        "alt": "sun",
        "title": "sun",
        "src": "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png",
        "data-description": "sun in photo"
    });
    

    and the same as

    $("<img>", {
        "data-id": 1,
        "alt": "sun",
        "title": "sun",
        "src": "http://cdn4.iconfinder.com/data/icons/iconsland-weather/PNG/48x48/Sunny.png",
        "data-description": "sun in photo"
    });
    

    which is exactly what the $("<img>", tool) is all about


    appendTo($toolbar); - jQuery appendTo

    simply append the result for each object in the tools array, into the $toolbar which might be a simple <div>