Muppet
Muppet

Reputation: 386

This object "undefined"

I've tried looking around and can't seem to find the same case so here's my problem:

Can anyone please help me with this simple error. Jquery is not my strongest suite but I feel like this is something small that I'm missing. With the code below I get the error 'undefined'.

html:

<a href='#' ><img src= "./images/1.jpg"  width= '200px'  id="2" rel="arm1" onclick = 'test()' /></a>

Jquery:

function test(){
    alert($(this).html());
};

What I want is the HTML code of the img tag being clicked on. Is there another way to do this?

So I've tried the following and it doesn't work as well: I've added the onclick to the ahref tag aswell.(error : undefined) I've tried passing by 'event' as a parameter. (error stating 'event' is not declared) when trying to get its html().

PS I do not want to use the id as a onclick function!

Anyhelp will be very much appreciated!

Thanks!

Upvotes: 2

Views: 105

Answers (2)

Johan Karlsson
Johan Karlsson

Reputation: 6476

this in your test() function refers to Window. To access the clicked element, try this:

HTML:

<element onclick='test(this)' />

JS:

function test(element){
    alert(element.innerHTML);
};

though clicking an <img> will not show you anything as its innerHTML will be empty.

Edit: As dsfq said, alert(element.outerHTML) will show you the HTML of your image.

Upvotes: 1

dfsq
dfsq

Reputation: 193261

All right, this is how you can get image HTML:

function test(obj) {
    alert($(obj).parent().html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">
    <img src= "http://lorempixel.com/100/100" onclick="test(this)" width="200px" id="2" rel="arm1" />
</a>

As you can see you can pass current image object to click handler as this. From there you go to parent element (a) and read its HTML content, which is going to be an image HTML.

UPD. t.niese in comments have a point about outerHTML, which has good support so the ideal code will look like:

alert(obj.outerHTML);

Upvotes: 2

Related Questions