简体   繁体   中英

Get ID name of a clicked element

This seems like it should be so simple but for some reason I can't get it working. I want to get the id of a clicked element.

The element:

<i id="fav6" onclick="changefave()" style="color: #DDD;" class="fa fa-star-o"></i>

The js:

function changefave(){
alert(this.id);
}

It's current returning, 'Undefined'.

Note: the element id is generated dynamically.

Thanks

You can change the onclick attribute of the <i> tag like:-

onclick="changefave(this);"

and the function like:

function changefave(obj) {
    alert(obj.id);
}

Yoy can try this

function changefave(obj) {
   alert(obj.id);
}

HTML

<i id="fav6" onclick="changefave(this)" style="color: #DDD;" class="fa fa-star-o">something</i>

DEMO

in html

<i id="fav6" onclick="changefave(this)" style="color: #DDD;" class="fa fa-star-o"></i>

in js

function changefave(this){
alert(this.id);
}

or by jQuery you can do

in html remove inline onclick

 <i id="fav6"  style="color: #DDD;" class="fa fa-star-o"></i>

and script will

$(document).ready(function(){
$("#fav6").click(function(){
alert($(this).attr("id");
});
});

Better not to do inline JavaScript. So, your HTML should be

<i id="fav6" style="color: #DDD;" class="fa fa-star-o"></i>

Then, in JavaScript:

$(function() { // waits for document and jQuery to load
    $('#fav6').on('click', function() {
        alert( $(this).prop('id') );
    });
});

try something like this

HTML CODE

        <i id="fav6" onclick="changefave(this);" style="color: #DDD;" class="fa fa-star-o"></i>

JAVASCRIPT CODE

        function changefave(obj){
            alert(obj.id);
        }

You need to pass it along with the "this" pointer as argument in the function call .

Hence your code in html should be

<i id="fav6" onclick="changefave(this)" style="color: #DDD;" class="fa fa-star-o"></i>

And the javascript function should be

function changefave(ele)
{
    // here ele refers to the called element 
    alert(ele.id);
}

Refer to this link to know more about 'this' https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM