Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image attrib inside a div?

Tags:

jquery

find

Say I have this:

 <div class='container'>
      <img src='image1' id='1' />
      <img src='image2' id='2' />
      ...
 </div>
 <div class='container'>
 </div>

Now, I when I click on the container, I want to get the id of the image inside it. If the container contains no image, it should pop up an error saying no images in the container. Otherwise, I would like to get a list of all the ids of the images inside.

Using jQuery, I have this:

 $('.container').click(function()
 {
      var images = $(this).find('img');
      if( images[0] == null ) { //no image found }
      else
      {
           // No idea what to do here :P
      }
 }

could someone please help me out here (I mean inside the else{} statement)? Thanks :)

like image 498
user1083320 Avatar asked Dec 27 '11 09:12

user1083320


1 Answers

$(document).on("click", ".container", function(){
    var img = $(this).find("img"), // select images inside .container
        len = img.length; // check if they exist
    if( len > 0 ){
        // images found, get id
        var attrID = img.first().attr("id"); // get id of first image
    } else {
        // images not found
    }
});

Example.

To get an array of the ids of all the images in the container:

var arr = []; // create array
if( len > 0 ){
    // images found, get id
    img.each(function(){ // run this for each image
        arr.push( $(this).attr("id") ); // push each image's id to the array
    });
} else {
    // images not found
}

Example.

And of course, what kind of a person would I be if I didn't give you an example with pure JS:

var elems = [].slice.call( document.getElementsByClassName("container") );
elems.forEach( function( elem ){
    elem.onclick = function(){
        var arr = [],
            imgs = [].slice.call( elem.getElementsByTagName("img") );
        if(imgs.length){
            imgs.forEach( function( img ){
                var attrID = img.id;
                arr.push(attrID);
            });
            alert(arr);
        } else {
            alert("No images found.");
        }
    };
});

Example. A bit more complex, and I still recommend to use jQuery since it clears up all the cross browser mouse event madness.

like image 51
Purag Avatar answered Oct 16 '22 10:10

Purag