1

I have following code:

HTML:

// import jQuery

<tr id = "tr_id">
  <td>something</td>
  <td>something</td>
</tr>

<div>
  <span class = "cls">something</span>
  <a id="a_id" href="#">something</a>
</div>

JavaScript:

var result;
$("tr, .cls").on("click", function(){

    if (/* selector is "tr" */) {
      result = $(this).attr("id");
    } else{
      result = $(this).closest("a").attr("id");
    }

});

Now I want to know how can I write a condition in this if statement?

if (/* selector is "tr" */) {
stack
  • 10,280
  • 19
  • 65
  • 117
  • Possible duplicate of [finding the type of an element using jQuery](http://stackoverflow.com/questions/608410/finding-the-type-of-an-element-using-jquery) – IlGala Mar 04 '16 at 18:45
  • 1
    `this.tagName` is a really fast way if you need perf – dandavis Mar 04 '16 at 18:47

1 Answers1

2

Try to use .is(selector) at this context,

$("tr, .cls").on("click", function(){
  var $this = $(this);
  result = $this.is("tr") ? $this.attr("id") : $this.closest("a").attr("id");
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 1
    re "_it has a function for everything_", yeah, and that's not even it's biggest problem ;) – dandavis Mar 04 '16 at 18:51
  • Sorry to ping you again, but in reality my code is different a bit. May you please tell me how can I use `.is()` in [this code](https://jsfiddle.net/to0zjLpo/) ? – stack Mar 04 '16 at 18:59
  • 1
    @stack Its ok man. Here you go. https://jsfiddle.net/to0zjLpo/1/ See the usage of `.bind()` in the code given. – Rajaprabhu Aravindasamy Mar 04 '16 at 19:01