user5671335
user5671335

Reputation: 85

Jquery get selector from on click

$('body').on('click', 'input, button, #el, li, .classTest, input[name=nametest], div > a.more', function(target) {
    console.log($(this).selector);
});

How do I implement a function selector(), that returns:

'input', if you click on input;
'button', if you click on button;
'li', if you click on li;
'.classTest', if you click on .classTest;
'input[name=nametest]', if you click on input[name=nametest];
'div > a.more', if you click on div > a.more;

Upvotes: 2

Views: 2632

Answers (2)

Jacob Brazeal
Jacob Brazeal

Reputation: 654

It's quite possible, but it requires a little more work since jQuery removed the .selector property in jQuery 1.9.

First, note that an element's full selector may be very long with many classes, an ID, another attributes, etc. You are only interested, I presume, in getting the matching selector that you passed to jQuery. Also, it's quite possible that the element matches multiple selectors; my answer controls for that by separating relevant selectors by a string; you may wish a more sophisticated combination.

I use .is() and a string variable containing your selector which you have access to in your event handler. The basic idea is, go through all the selectors and concatenate the ones that match $(element).is(selector).

function selector ( element, selectorList ) {
      var selector = "";
      for ( var i=0; i<selectorList.length; ++i ) {     
            if ( $(element).is(selectorList[i]) ) {
                if ( selector.length && selector[selector.length-1] != "," ) { selector += ","; }
                selector += selectorList[i];
            }
      }
      return selector;
}

$("document").ready(function(){
  
var selectorList = 'input, button, #el, li, .classTest, input[name=nametest], div > a.more';

$('body').on('click', selectorList, function(target) {
     alert(selector(this,selectorList.split(",")));
});
  
});
* { cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Click me!</button>

<div id='el' >This is #el, click me</div>

Upvotes: 1

Geeky
Geeky

Reputation: 7488

Check the following code snippet

$(document).ready(function(){
  $('body').on('click', function(event) {
   var target=event.target;
    alert(target.type);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
<input type="button" value="Click">

Hope this helps

Upvotes: 1

Related Questions