Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get attribute of div without ID

My website contain lot of images and thats why i cannot give ID for each image it will be tedious task. I need to get the source attribute of image tag but i am not able to do it without ID. I did try for attr() and getAttribute() but it doesn`t seems to work for me.

My Code

<img src="./images/image1.jpg" width='100' height='100' alt='Sample image' onClick='imageInfo(this);'>

<script>
function imageInfo()
{
    alert(this.src);
}
</script>

i am trying to get the source of image tag but it is not coming i have also tried in jsfiddle but it is not working .

JS FIDDLE LINK

like image 574
Hitesh Avatar asked Nov 28 '22 15:11

Hitesh


2 Answers

try something like this. Because you have passed the object of image but not used in function

<script>
    function imageInfo(obj)
    {
        alert(obj.src);
    }
</script>
like image 117
rajesh kakawat Avatar answered Dec 09 '22 03:12

rajesh kakawat


From your fiddle,

function imageInfo(this)
{
    alert('image');
    alert(this.src);
}

This happened because of this is a reserved keyword.

 function imageInfo (e)
{
    alert('image');
    alert(e.src);
}

Also onclick not onClick, to know the reason check this SO answer

check this Fiddle

like image 37
Praveen Avatar answered Dec 09 '22 05:12

Praveen