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 :)
$(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 id
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With