user1234
user1234

Reputation: 3159

How to get the rowIndex of a div element clicked

I want to get the rowIndex of the <div> I clicked.

<div id="parent" onClick="this.click()">
    <div id="1">
      <span text="22"></span>
    </div>
    <div id="2"><span text="32"></span></div>
    <div id="3"><span text="232"></span></div>
    <div id="4"><span text="242"></span></div>
    <div id="5"><span text="252"></span></div>
</div>

I'm at a stage where I get the <div> I have clicked, lets say I have:

<div id="3"><span text="232"></div>

How can I get the id and the value of the text in the <span> inside that <div>?

Upvotes: 0

Views: 729

Answers (2)

beta programmers
beta programmers

Reputation: 653

If you are using Jquery, this will work [Tested]:

$("#parent").find('span').each(function(){
        $(this).on('click', function(){
            console.log($(this).parent().attr('id'));
        });
    });

Let me know if any issues with this

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192277

Add an event handler to the container (#parent) using Element.addEventListener(). When the handler is triggered, check if the event target is a span Element.matches().

If it is, get the id from the parent node (the div), and the text attribute from the span, using Element.getAttribute():

var container = document.getElementById('parent');

container.addEventListener('click', function(e) {
  if (!e.target.matches('#parent > div > span')) return;
  
  var id = e.target.parentNode.id;
  var text = e.target.getAttribute('text');
  
  console.log(id, text);
});
<div id="parent">
  <div id="1">
    <span text="22">1</span>
  </div>
  <div id="2"><span text="32">2</span></div>
  <div id="3"><span text="232">3</span></div>
  <div id="4"><span text="242">4</span></div>
  <div id="5"><span text="252">5</span></div>
</div>

Upvotes: 1

Related Questions