0

I use $('[attribute]') to select html nodes. When I am using the nodes it would be nice to know which html element was selected.

Pseudo code:

$('body').on('click', '[action]', function(){
    var htmlElementName = this.name;

    if(htmlElementName == 'form'){
        return;
    }

            //do stuff

});
botenvouwer
  • 3,658
  • 7
  • 38
  • 67

4 Answers4

6

Just get the value of a tagName property:

var htmlElementName = this.tagName;

REF: https://developer.mozilla.org/en-US/docs/Web/API/Element.tagName

VisioN
  • 132,029
  • 27
  • 254
  • 262
3

As per the title, in jQuery specifically

$(this).prop('tagName');

the native version seems simpler

this.tagName

note that case might vary, so using toLowerCase() is generally a good idea

adeneo
  • 293,187
  • 26
  • 361
  • 361
  • According to the [**MDN**](https://developer.mozilla.org/en-US/docs/Web/API/Element.tagName#Example) the case varies only for HTML and XML: *"In XHTML (or any other XML format), "span" would be alerted. In HTML, "SPAN" would be alerted instead."*. So if the OP works with a proper HTML document the name in capitals should be returned. – VisioN Dec 20 '13 at 12:39
  • @VisioN - that's why it might vary, I always chain on a toLowerCase() to avoid issues, as I can never remember when it's lowercase and when it's uppercase. – adeneo Dec 20 '13 at 12:42
  • Interesting that you don't use `toUpperCase()` instead `;)` – VisioN Dec 20 '13 at 12:43
  • @VisioN - Actually, I've created my own custom `toCamelCase()` that I use `;)` – adeneo Dec 20 '13 at 12:48
  • BTW did you know that [jQuery has its own implementation](http://stackoverflow.com/a/14345461/1249581) of `toCamelCase`? – VisioN Dec 20 '13 at 13:06
2

You can use this.tagName

$('body').on('click', '[action]', function(){
    var htmlElementName = this.name;
    var tagName = this.tagName;
    if(htmlElementName == 'form'){
        return;
    }       //do stuff    
});
Adil
  • 139,325
  • 23
  • 196
  • 197
0

Try this:

$('body').on('click', '[action]', function(e){

    var htmlElementName = $(this).prop("tagName");

});
Mr.G
  • 3,023
  • 2
  • 14
  • 19