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
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")){
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")
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With