1

I am adding a class dynamically to some elements. And i need to get the innerHTML of the clicked element where the added class is present. Can anyone have any idea of how to get the innerhtml with refer to class?

Please note that i don't want to use any Javascript libraries like jQuery.

5
  • 1
    stackoverflow.com/a/4589863/362536 Commented Jul 15, 2012 at 4:37
  • Look here maybe helps [stackoverflow.com/questions/4164053/… [1]: stackoverflow.com/questions/4164053/… Commented Jul 15, 2012 at 4:38
  • @Brad It is only working for the immediate element. For eg. If i have a div inside myclass which is having some other class name, than it is not triggering. Commented Jul 15, 2012 at 4:54
  • @GTSouza Those solutions are given with refernce to id. But i need that for class. Commented Jul 15, 2012 at 4:58
  • @nnnnnn I want to do something when both <i>x</i> or any of its descendent is clicked. Commented Jul 15, 2012 at 5:15

1 Answer 1

3

Try this:

document.body.onclick = function(e) {
    var clickedEl = window.event ? event.srcElement : e.target;
    while (clickedEl != null) {
        if (clickedEl.className
            && (" " + clickedEl.className + " ").indexOf(" yourclass ") != -1) {
            // do something, e.g.,
            alert("Element with class was clicked");
            return;
        }
        clickedEl = clickedEl.parentNode;
    }
}​

Demo: http://jsfiddle.net/3qChA/

This will do "something" (in my example show an alert) when any element with class "yourclass" is clicked, or when any descendant element of an element with "yourclass" is clicked. Obviously you can replace the hard-coded "yourclass" with a variable as appropriate.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.