0

I currently have a list of <li>'s. Each <li> will have a color class defined, example: .color-blue, .color-red, .color-green - like so:

<ul id="listings">
  <li class="layer block color-blue" id="item-1"></li>
  <li class="layer block color-red" id="item-2"></li>
  <li class="layer block color-green" id="item-3"></li>
</ul>

How do I copy/get the color class of the specific <li> item that is clicked?

I have my click listener in place and also know how to get the <li "id"> however not sure on the specific class though.

/* Click listener */
document.getElementById("listings").addEventListener("click", function(e) {
  //console.log(e.target.id + " was clicked");
});
user1231561
  • 3,239
  • 6
  • 36
  • 55
  • Just read the className out, see this: http://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class – Andrew Feb 24 '14 at 09:33

4 Answers4

0

You can use (jQuery):

$('ul').find('li.layer block color-blue')

Or

$('ul#listings').find('li.layer block color-blue')
Java_User
  • 1,303
  • 3
  • 27
  • 38
0

Try

document.getElementById("listings").addEventListener("click", function(e) {
   alert(e.srcElement.className);
});

DEMO

UPDATE(since it is not working in Firefox as pointed from Sai):

To work also in Firefox try this:

document.getElementById("listings").addEventListener("click", function(e) {
   var target = e.target || e.srcElement;
   alert(target.className);
});

DEMO2

laaposto
  • 11,835
  • 15
  • 54
  • 71
0

Or... you can not use jQuery as that wasn't in the original question and would be wasteful to include unnecessarily.

Here's a solution that works in vanilla JS: jsFiddle Example

Essentially because you're lumping the colour among the other classes you have to split them into an array and iterate over them until you find the one that starts 'color-'. I would recommend you use a custom attribute instead, like data-color="blue" as that would mean you could just retrieve it with:

e.target.getAttribute('data-color');
toomanyredirects
  • 1,972
  • 15
  • 23
0

Something like this:

document.getElementById("listings").addEventListener("click", function(e) {
    var el = e.target;
    if (el.tagName == "LI") { // Use only li tags
        for (i=0; i < el.classList.length; i++) {
            if (~el.classList[i].indexOf('color')) {
                var color = el.classList[i];
                console.log('color class found: '+color);
                break;
            }
        }
    }
});

http://jsfiddle.net/bHJ3n/

Goran.it
  • 5,991
  • 2
  • 23
  • 25