skip to Main Content

Sorry for this silly question, newbie here.

I’m trying to do a testing and I want to insert the element name and ALT text values into var tagged ={} object.

var $img = $(‘#gallery img’);
var tagged = {};

$img.each(function(el, val) {
   
    tagged[el] = val  <-----this is the part where I'm lost
})
console.log("tagged result : ", tagged);

My goal is to have this result like: {img, picture1, img, picture2}

2

Answers


  1. You intend to create an object of key-value pairs, where the value is the image element. It’s unclear to me what the keys should be, but basically you can use any key you want as you have a solid idea of what the end-result you want to achieve is. Your original code created an index for the images and that index was being used as the key. In my example the images have a title each and I use it as the key.

    $(function() {
        var $img = $('#gallery img'); var tagged = {};
    
        $img.each(function(el, val) {
       
            tagged[this.title] = val;
        })
        console.log("tagged result : ", tagged);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="gallery">
        <img title="forest from afar" src="https://media.cntraveler.com/photos/5eb18e42fc043ed5d9779733/16:9/w_1920%2Cc_limit/BlackForest-Germany-GettyImages-147180370.jpg">
        <img title="rolling on the river" src="https://media.cntraveler.com/photos/592debf3a67ebe23dff78b2f/master/w_1920%2Cc_limit/amazon-rainforest-GettyImages-137578327.jpg">
    </div>

    Images were taken from here: https://www.cntraveler.com/gallery/the-most-beautiful-forests-in-the-world

    Login or Signup to reply.
  2. It is not completely clear what your ask. Here is a suggestion

    var $img = $('#gallery img');
    var tagged = {};
    $img.each(function(idx, el) {
      tagged[el.id] = {[el.tagName]:el.alt}; 
    })
    console.log("tagged result : ", tagged);
    
    // or
    
    tagged = []
    $img.each(function(idx, el) {
      tagged.push({[el.id]:el.alt}); 
    })
    console.log("tagged result : ", tagged);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="gallery">
      <img id="img1" src="test1.jpg" alt="img alt 1" />
      <img id="img2" src="test2.jpg" alt="img alt 2" />
      <img id="img3" src="test3.jpg" alt="img alt 3" />
     </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search