qadenza
qadenza

Reputation: 9293

get index of specific tag

How can I get index of clicked paragraph only, without calculating index of textareas ?

html code:

<div class="story">
<p>index is 0, that's ok</p>
<textarea></textarea>
<p>index is 2, should be 1</p>
<textarea></textarea>
<p>index is 4, should be 2</p>
</div>

js:

$(".story > p").click(function() {
    var a = $(this).index();
    alert (a);
});

Upvotes: 2

Views: 186

Answers (3)

Yoni Mor
Yoni Mor

Reputation: 354

var pTags = document.querySelectorAll('.story p');

function printIndex(i) {
  console.log(i);
}

for (var i = 0; i < pTags.length; i++) {
  pTags[i].addEventListener("click", printIndex.bind(this, i));
}

Upvotes: 0

Andreas
Andreas

Reputation: 21881

$.index(selector): A selector representing a jQuery collection in which to look for an element.

$(".story > p").click(function() {
    var a = $(this).index("p");
    alert (a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="story">
<p>index is 0, that's ok</p>
<textarea></textarea>
<p>index is 2, should be 1</p>
<textarea></textarea>
<p>index is 4, should be 2</p>
</div>

Upvotes: 3

iplus26
iplus26

Reputation: 2637

In native way:

var els = document.querySelectorAll('.story > p');

Array.prototype.slice.call(els).forEach(function(el, i) {
  el.addEventListener('click', function() {
    alert(i);  // in this case, alert 0, 1, 2
  });
})
<div class="story">
<p>index is 0, that's ok</p>
<textarea></textarea>
<p>index is 2, should be 1</p>
<textarea></textarea>
<p>index is 4, should be 2</p>
</div>

Upvotes: 0

Related Questions