Get clicked class index javascript

get index of class jquery
get index of clicked element javascript
jquery get array value by index
javascript get index of element in parent
jquery find what child index
javascript find index of object in array by property
jquery find index of object in array
div index

I have 3 divs with class: wpEdit and onClick: alertName()

<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>

When clicked i want to know the Index of class wpEdit of the clicked Div:

function alertName(){
    //Something like this
    var classIndex = this.className.index; // This obviously dosnt work
    alert(classIndex); 
}

when clicked on Bruce Lee it should alert : 0 when clicked on Jackie Chan it should alert : 1 when clicked on Jet Li it should alert : 2

I need to know which instance of class="wpEdit" is clicked on

Try this

function clickedClassHandler(name,callback) {

    // apply click handler to all elements with matching className
    var allElements = document.body.getElementsByTagName("*");

    for(var x = 0, len = allElements.length; x < len; x++) {
        if(allElements[x].className == name) {
            allElements[x].onclick = handleClick;
        }
    }

    function handleClick() {
        var elmParent = this.parentNode;
        var parentChilds = elmParent.childNodes;
        var index = 0;

        for(var x = 0; x < parentChilds.length; x++) {
            if(parentChilds[x] == this) {
                break;
            }

            if(parentChilds[x].className == name) {
                index++;
            }
        }

        callback.call(this,index);
    }
}

Usage:

clickedClassHandler("wpEdit",function(index){
    // do something with the index
    alert(index);

    // 'this' refers to the element 
    // so you could do something with the element itself
    this.style.backgroundColor = 'orange';
});

.index(), The complementary operation to .get() , which accepts an index and returns a DOM node, On click, returns the index (zero-based) of that div in the page. Many 3rd party JavaScript libraries allow you to select all elements that have a CSS class of a particular name applied to them. Then you can iterate those elements and dynamically attach the handler.

The first thing you might want to address in your code is the inline HTML binding.

You could use document.addEventListener on each element, or rely on event delegation.

The widely most used implementation of event delegation comes with jQuery. If you're already using jQuery, this is the way to go!

Alternatively I've also my own little delegate utility.

const delegate = (fn, selector) => {
  return function handler(event) {
    const matchingEl = matches(event.target, selector, this);
    if(matchingEl != null){
      fn.call(matchingEl, event);
    }
  };
};

const matches = (target, selector, boundElement) => {
  if (target === boundElement){
    return null;
  }
  if (target.matches(selector)){
    return target;
  }
  if (target.parentNode){
    return matches(target.parentNode, selector, boundElement);
  }
  return null;
};

This is how you would register the event listener.

document.getElementById('#parent')
  .addEventListener('click', delegate(handler, '.wpEdit'));

And this is how you could get the index of the element that generated the event.

const handler = (event) => {
  console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}

Live demo:

const delegate = (fn, selector) => {
  return function handler(event) {
    const matchingEl = matches(event.target, selector, this);
    if (matchingEl != null) {
      fn.call(matchingEl, event);
    }
  };
};

const matches = (target, selector, boundElement) => {
  if (target === boundElement) {
    return null;
  }
  if (target.matches(selector)) {
    return target;
  }
  if (target.parentNode) {
    return matches(target.parentNode, selector, boundElement);
  }
  return null;
};

const handler = (event) => {
  console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}

document.getElementById('parent')
  .addEventListener('click', delegate(handler, '.wpEdit'));
<div id="parent">
  <div class="wpEdit">Bruce Lee</div>
  <div class="wpEdit">Jackie Chan</div>
  <div class="wpEdit">Jet li</div>
</div>

get index of same class element on click, so based on this class only i am getting the click event on them. now what I want is to get the index of one single div one which we clicked.. is it  I would like to get the current element (whatever element that is) in an HTML document that I clicked. But very strangely, I get the text of the whole (!) document, not the clicked element. How to get only the element I clicked on? If I click on the "test" text, I would like to be able to read the attribute with $ (this).attr ("myclass") in jQuery.

If you want the index of the div's based on your class wpEdit you can do like this:

HTML:

<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="other">Other</div>
<div class="wpEdit">Jet li</div>

JS:

$(".wpEdit").bind("click", function(){
    var divs = $(".wpEdit");
    var curIdx = divs.index($(this));

    alert(curIdx);
});

Live example : http://jsfiddle.net/pJwzc/

More information on the index function of jQuery : http://api.jquery.com/index/

jQuery Misc index() Method, Example. Get the index of the clicked <li> element, relative to its siblings: $("li").​click(function(){ alert($(this).index()); });. Try it Yourself »  Another Native JS way to do this is using TableData properties that can be found when using table elements. For example, cellIndex will return the column index of a td element and rowIndex will return the index of a tr element. These two properties will simplify our code by a ton, shown on the following code.

Using vanilla javascript, this one works for me:

var wpEdits = document.querySelectorAll(".wpEdit");

for (let i = 0; i < wpEdits.length; i++)
  wpEdits[i].addEventListener("click", showID);

function showID(evt) {
  for (let i = 0; i < wpEdits.length; i++)
    if(wpEdits[i] == evt.target)    
      alert(i);
}

May not be the best solution though as I am still new to js.

Since I am very new to JS, take the following explanation with a grain of salt:

(Line-1) This is similar to var wpEdits = document.getElementsByClassName("wpEdit");. It will assign all instances of class="wpEdit" from the html file to the wpEdits variable.

(Line-3 and Line-4) This two lines will cause any click on the class="wpEdit" to call function showID() defined below.

(Line-6 and Line-10) When a click event happens, the browser will pass the unique properties of the item being clicked to the evt variable. This then is used in the for loop to compare against all available instances incrementally. The evt.target is used to get to the actual target. Once a match is found, it will alert the user.

To avoid wasting CPU time, running a break; is recommended to exit the loop soon after the match is found.

jQuery addClass() Method, Example. Add a class name to the first <p> element: $("button").click(function(){ $(​"p:first").addClass("intro"); });. Try it Yourself »  Definition and Usage. The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0. Tip: You can use the length property

I could not understand, why people add new functions in previous answers, so...

const wpEdit = document.getElementsByClassName('wpEdit');
for(let i = 0; i < wpEdit.length; i++){
  wpEdit[i].addEventListener('click',function(){
    alert(i);
  });
}

I just added 'click' event, using the loop. And [i] already is the current clicked class index...

FIDDLE

Find the index of the element that was clicked with jQuery, There may be times when you need to know the index of the element that is clicked from within a group of elements e.g. a group of divs inside another div. home Front End HTML CSS JavaScript HTML5 Schema.org php.js Twitter Bootstrap Responsive Web Design tutorial Zurb Foundation 3 tutorials Pure CSS HTML5 Canvas JavaScript Course Icon Angular React Vue Jest Mocha NPM Yarn Back End PHP Python Java Node.js Ruby C programming PHP Composer Laravel PHPUnit ASP.NET Database SQL(2003 standard of ANSI

How to get the ID of the clicked button using JavaScript / jQuery , Get the ID of clicked button using JavaScript. Example 1: This example sets a onClick event to each button, when button is clicked, the ID of the button is passed  Find the index of the element that was clicked with jQuery There may be times when you need to know the index of the element that is clicked from within a group of elements e.g. a group of divs inside another div.

JQuery: Selecting index of currently clicked item from inside another , Hi all, I'm trying to find the currently clicked index of .accordion_trigger from within another element. When inside the .accordion_trigger click event I can simply  I have some list item, and I want know which one is clicked by user, so I set onClik on every item, and I user event.target to get the node clicked, but I get this issue, my items has children nodes, when user click the childre

How to Get the ID of an Element using jQuery, You can simply use the jQuery attr() method to get or set the ID attribute value of an example will display the ID of the DIV element in an alert box on button click​. <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> You can also get the ID of individual element when using class selector based on index  Syntax and Usage of onclick. When onclick Is Used. The onclick JavaScript event occurs when the user clicks on an element. It runs a specified line of code when you click a HTML object that has the onclick attribute. The JavaScript onclick functions can be triggered by object.onclick or object.addEventListener.

Comments
  • i want to do it by pure js, but if not jQuery is cool
  • WoW I was looking for a way to find the current index in a set of elements through vanilla JS. I stumbled upon stackoverflow.com/a/1933609/1606729 but I wouldn't have written such a good answer
  • .. and I just found out what Vanilla JS is
  • I was really wondering what was not "vanilla" in your example ^^ Glad he accepted your answer in the end!
  • No one mentioned jQuery.
  • jQuery would be the easiest way to accomplish this.
  • No one mentionned explicitely "I want to do this in pure javascript" either. I don't see the problem in giving a working answer, I don't know how to do this in pure javascript but I'm searching.
  • since i think he only used javascript tag
  • He might have only used javascript tags because he doesn't even know about jQuery. I explained I'm using jQuery and gave a link to the function.
  • Hi Afdhal, and welcome to Stack Overflow! Can you provide a brief explanation of how/why this works, beyond just providing the code? Thanks!
  • Thank you for the warm welcome @MaxvonHippel ! Forgive me for not explaining the code. I am very new to JS and I don't think I am qualified to explain it as I worry it might confuse others. I will do my best to explain it this time.