Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: hasClass partial match

When using Attribute Contains Word Selector is it supposed to evaluate to true? I'm trying to use it in an if/else statement like the one below and it is not evaluating to true.

<li class="orange blue">
    <div class="answer">Some Content</div>
</li>
<input type="button" name="yellow" value="yellow" class="yellow" />
<br />
<input type="text" value="" class="result" />

$("input.yellow").click(function() {
    if ( $("div.answer").parent().hasClass($("[class~='bl']")) == true ){
        $("input.result").val("has class");
    } else {
        $("div.answer").parent().addClass("blue");
        $("input.result").val("class added")
    };
});

The fiddle

like image 397
pn03 Avatar asked Feb 22 '26 18:02

pn03


2 Answers

As the comment advised, hasClass takes in a string. so you could use is:-

if ( $("div.answer").parent().is($("[class~='bl']"))){

or you could create a little jquery plugin:-

$.fn.hasPartialClass = function(partial){
  return new RegExp(partial).test(this.prop('class')); 
};

and use like:-

if ( $("div.answer").parent().hasPartialClass("bl")){
like image 137
BenG Avatar answered Feb 24 '26 09:02

BenG


You forgot that you are using the "Attribute Contains Word Selector" So for this selector to match you have to use [class~='blue']. You can't use [class~='bl'], because the class attribute does'nt contain the word 'bl' but the word 'blue'.

The way to use this selector :

    $("input.yellow").click(function() {
    if ( $("div.answer").parent().is("[class~='blue']") ){
        $("input.result").val("has class");
    } else {
        $("div.answer").parent().addClass("blue");
        $("input.result").val("class added")
    };
});
like image 20
Hedi Avatar answered Feb 24 '26 09:02

Hedi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!