ali reza
ali reza

Reputation: 57

inspect element with jquery

i want to get id(or class) of element when i clicked on that. i write this codes.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script>
  $(document).ready(function() {
    $('*').click(function() {
      var idName = $(this).attr('class');
      alert(idName);
    });
  });
</script>
<div class="test">
  <div class="test1">
    <div class="test2">
      test
    </div>
  </div>
</div>

but it give me class(id) of parent class.(and undefined) how i can delete that?(give me just class(or id) of one element)

Upvotes: 2

Views: 1264

Answers (3)

Brino
Brino

Reputation: 2502

Use .attr('class') for class(es), and .attr('id') for the id. I updated your example below.

When you click on an element, the click will propogate down through all containing elements and will trigger the click function for each one. To stop propagation use .stopPropagation().

  $().ready(function() {
    $('*').click(function(e) {
      var classNames = $(this).attr('class');
      var idName = $(this).attr('id');
      alert('ID: ' + idName + '\r\nClasses: ' + classNames);
      e.stopPropagation();
    });
  });
#a {
  width: 200px;
  height: 100px;
}
div {
  border: 2px solid black;
  border-sizing: border-box;
  padding: 4px;
}
#a div {
  width: 100%;
  height: 100%;
}
.test {
  background-color: green;
}
.test1 {
  background-color: red;
}
.test2 {
  background-color: orange;
}
.class1 {
  text-decoration: underline overline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<div id="a" class="test">test
  <div id="b" class="test1 class1">test1
    <div id="c" class="test2 class1">
      test2
    </div>
  </div>
</div>

Upvotes: 1

omikes
omikes

Reputation: 8513

Or make it just show ids for each element:

$('*').click(function(event) {
  event.stopPropagation();
  var ident = $(event.target).attr('id');
  alert("id = " + ident);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">button</button>
<br>
<br>
<input type="textbox" id="textbox" placeholder="textbox" />
<br>
<br>
<span id="text">text</span>

Upvotes: 1

taxicala
taxicala

Reputation: 21769

Add event.stopPropagation and use event.target:

  $(document).ready(function() {
    $('*').click(function(e) {
      e.stopPropagation();
      var idName = $(e.target).attr('class');
      alert(idName);
    });
  });

Upvotes: 1

Related Questions