Who am I or How do I know which Element I am facing?

hey take a look at this code:

$("li,p").click(function(){

   // how do I perform a test, and know wich Element it is ?

   if( /* I'm a <li/> */ )
       // Do this for the <li/>

   if( /* I'm a <p/> */ )
       // Do this for the <p/>
})

thanks guys ^^

+3
source share
4 answers

One option is to use the is () method :

$("li,p").click(function(){

   // how do I do I perform a test, on wich Element it is ?

   if($(this).is('li'))
       // Do this for the <li/>

   if($(this).is('p'))
       // Do this for the <p/>
})
+6
source

You are looking for this.nodeName.

You can also write

if (jQuery.nodeName(this, 'p'))
+3
source

Live demo

$("li,p").click(function(){
    if(this.tagName.toLowerCase() == "p"){
       alert("PP!");
    }else if(this.tagName.toLowerCase() == "li"){
        alert("list!");
    }
})
+1
source

Use function is()

$("li,p").click(function(){         

    if( $(this).is('li') )        
        // Do this for the <li/>     
    if( $(this).is('p') )        
        // Do this for the <p/> 
});
+1
source

All Articles