Kaja Mydeen Kaja Mydeen - 4 months ago 9
Javascript Question

How to get the position of the clicking Tag?

I would like to get the position of clicked element position. If i clicked First p tag, the alert box have to give output 1. if i clicked some text p tag then it should give output 3. I don't know how to do it. Please anyone give me solution. Thanks in advance.

Below is my HTML code.

<div class="wrapper">
<p>First</p>
<p>Second</p>
<p>Some text</p>
</div>


Below is my JQuery code

<script src="jquery.js"></script>
<script>
$('p').click(function() {
alert("You clicked nth position tag");
});
</script>

Answer

You can use .index():

$('p').on('click', function() {
  //add 1 to get the desired result 
  //because index starts from 0 
  console.log($(this).index() + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <p>First</p>
  <p>Second</p>
  <p>Some text</p>
</div>

For your new requirement you can use .text():

$('p').on('click', function() {
  console.log(`You clicked ${$(this).index() + 1} nth position tag with text: ${$(this).text()}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <p>First</p>
  <p>Second</p>
  <p>Some text</p>
</div>

I used template literal but you can simple use string concatenation.