Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript switch statement, if string contains substring

I'm trying to figure out how to do a switch statement where I need to find a class name of the object, then do something depending on the class name (in the switch statement).

In this example, I need the switch statement to do whatever I need when the class contains a specific word, such as "person".

html

<div class="person temp something"></div>

javascript

$(document).on('mousedown', function(e) {
    var clicked = $(e.target).attr('class');
    console.log(clicked);
    switch (clicked) {
        case "person":
            //do something
            break;
        default:    
            //do something  
    }
});

It's not guaranteed that the switch statement name, such as "person" will be in the first spot.

I know I can search through an array for a specific word, but I don't know how to add that to this sort of thing.

like image 290
ntgCleaner Avatar asked Dec 20 '22 12:12

ntgCleaner


1 Answers

As I said in my comment, a switch statement doesn't appear the appropriate approach in this situation.

Since you are using jQuery, just use .hasClass:

if ($(e.target).hasClass('person')) {
  // do something
}

If you want to do something more complicated for multiple classes, you can create a class -> function mapping and simply iterate over the class list:

var classActions = {
    person: function(element) { /* do something */ },
    temp: function(element) { /* do something */},
    // ...
};

var classes = e.target.className.split(/\s+/);
$.each(classes, function(index, cls) {
    classActions[cls](e.target);
});
like image 76
Felix Kling Avatar answered Jan 10 '23 04:01

Felix Kling