Detect which item to click

In short, I am loading a local HTML page in divinside another web form in asp.net.

JQuery:

<script>
    $(function () {
        $("#includedContent").load("../HtmlHolder/index.html");
    });

</script>  

HTML:

  <div id="includedContent" class="WebHolder" style="width: 450px; height: 300px; border: 1px solid #808080; margin: 0px auto; overflow-y: scroll;"></div>

Now I want to get the class name of the element by clicking on it below the script:

<script>
    $(document).ready(function () {
        $('.WebHolder').on("click", "*", function (e) {

            alert("Class :" + $(this).attr("class"));
        });
    });
</script>  

My problem is that when I click on any element, this code warns this class name and its parent!

How to solve it?

Note: the item is not a specific object, it may be an input or button or text area or ....

+4
source share
2 answers

You should use e.target(use this as a selector), not this(because it's the parent)

alert("Class :" + $(e.target).attr("class"));

: this e.target, , .

if( this !== e.target )

CODE SNIPPET FOR DEMO:

$('div').on('click', function(e){

    if( this !== e.target ) alert( 'Class is '+ $(e.target).attr('class') );

});
div{
  background: #fe7a15; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  
  I am the parent, Clicking me will not get you an alert but headers does, because they are my children.
  <br /><br />
  <h1 class="class-header-child-one">Header 1</h1>
  <h2 class="class-header-child-two">Header 2</h2>
  
</div>
Hide result
+9

event.stopPropagation() .

$('.WebHolder').on("click", "*", function (e) {

    alert("Class :" + $(this).attr("class"));
    e.stopPropagation();
});

, DOM.

Demo:

$(document.body).on('click', '*', function(e) {
    alert($(this).text());
    e.stopPropagation();
});
div {
  background: red;
}
div > div {
  background: orange;
}
div > div > div {
  background: yellow;
}
div > div > div > div {
  background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Main
    <div>1
        <div>11</div>
        <div>12</div>
        <div>13
            <div>131</div>
        </div>
    </div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>
Hide result
+3

All Articles