Jquery If element has class which begins with x, then don't addClass

后端 未结 4 820

I\'m a definite newbie, so apologies for rubbish coding! I\'ve written the following Jquery for a practice project I set myself:

When you click on the div, it has t

相关标签:
4条回答
  • 2020-12-16 13:18

    The other answers do not work if your element has multiple classes on the same element. You need to select it as such:

    if ( $(this).is('[class^="bleh_"], [class*=" bleh_"]') ) {
    
        // Return true if element has class that starts with "bleh_"
    
        // Note: The second argument has a space before 'bleh_'
    
    }
    
    0 讨论(0)
  • 2020-12-16 13:27

    I think the matter is in the if condition :

    if(!$(this).hasClass('[class^="answerbox"]')) {
    

    Try this :

    if(!$(this).is('[class*="answerbox"]')) {
        //Finds element with no answerbox class
    } else {
        //The element has already an answerbox class
    }
    

    You should take a look at toggleClass and is jquery docs.

    See this live fiddle example.

    Little tip : instead of n = (n + 1) you can do n++ :).

    Edit :

    After reading again the question, I did a full working script :

    Assuming the Html is :

    <div id="box">
        <p>Answer1</p>
        <p>Answer2</p>
        <p>Answer3</p>
    </div>
    
    <div id="answerbox">
    
    </div>
    

    jQuery :

    var n = 0;
    
    $('#box p').on('click',function(e) {
        e.preventDefault();
        if(!$(this).is('[class*="answerbox"]')) {
            n++;
            $(this).addClass('in_answerbox' + n );
            $(this).clone().appendTo('#answerbox').addClass('answerbox_letter' + n); 
        }
    });
    

    See this example here.

    You should consider using data-attributes, they'll be more reliable then classes for what you're trying to do.


    Note that if you want the selector to match only if the class attribute begins with a word, you'll want [class^="word"]. * however searches through the whole class attribute. Be careful though, [class^="word"] will not match <div class="test word"> see here.

    0 讨论(0)
  • Use .is() instead of .hasClass(). The former can be used with CSS selectors whereas the latter can only use class name as a "fixed" string.

    if(!$(this).is('[class^="answerbox"]'))
    

    NOTE: This will only work consistently if the element has exactly one class

    0 讨论(0)
  • 2020-12-16 13:37

    If you need something that works for multiple class names, check this

    var theClasses = $(this).attr('class').split(" ");
    var i=0;
    var found = false;
    while(i<theClasses.length && !found) {
       if(theClasses[i].indexOf('answerbox') == 0) {   // starts with answerbox
          found = true;
       }
       i++;
    }
    if(!found) {
       // the current element does not have a class starting with answerbox
    }
    
    0 讨论(0)
提交回复
热议问题