Set a bool variable if an element has a class applied - javascript

I am able to hide an element on the page in this way
$('.info_player > .item_focus').hide();
I need to set a variable on true or false if the element .info_player has the class .item_focus applied or not.
How to make it with jquery?
Please provide me a sample of code

var hasClassItemFocus = $('.info_player > .item_focus').length > 0;
hasClassItemFocus will be true if .info_player has .item_focus as a class.

You describe different things in your code and description:
$('.info_player > .item_focus').hide();
means you have the elements like the below
...
<div class="info_player">
<div class="item_focus">
...
"if the element .info_player has the class .item_focus applied or not"
means the following:
div class="info_player item_focus"
For the latter case you can use hasClass method.
In the former case you can use $('.info_player > .item_focus').length or $('.info_player').find('.item_focus').length and more. Jquery provides multiple ways to do the same things.

you can use jquery .hasClass()
if($('.info_player').hasClass('item_focus'))
{
var a = value;
}
or by one line
var a = $('.info_player').hasClass('item_focus') ? "a" : "b";

Related

Hiding content depending on variable value

I am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});

check if class does not exist on any of data- items

I have a list of div elements with a data-windows attribute:
I basically want to check if any of these are not hidden (and doing something if they are all hidden)
I'm looping through them like so, this works but I'm wondering if there's a more efficient way:
$("[data-windows]").each(function () {
if (!$(this).hasClass('hidden')) {
isSomethingShown = true;
return false;
}
});
You can use :visible pseudo selector :
if($("[data-windows]:visible").length){
//Atleast 1 is visible
}else{
//All hiden
}
or
var isSomethingShown = !!$("[data-windows]:visible").length; // Bang!Bang! [!!] convert into a boolean
Of course, if you want to explicitly check the class, both selector can be change to (and maybe should be for faster performance) $("[data-windows].hidden")
how bout this oneliner:
return $("[data-windows].hidden").length == 0 ? false : true;

How to bypass function for element with specify class and two conditions with jQuery

It's hard to say in couple wors in title... So i have this code:
var class_main_content = $('.main_content ul').attr('class');
var xml_element_name = $(xml).find(class_main_content)[0].nodeName.toLowerCase();
var no_option = $('.no_option').attr('class');
if ((class_main_content) == xml_element_name){
...
}
else if ($(class_main_content) == (no_option)){
...
}
and i have first condition with some actions - every things fine, next i have second condition which first condition is also performs, but i need to do something for element with class .no_option. The problem grows when this element have two class from first condition and second. How to pass by first condition and do something for second? :)
Rather than getting the class attribute and comparing it against things, why not use the hasClass JQuery function:
var main_content=$('.main_content ul');
if(main_content.hasClass('something')) {
do_something();
}
if(main_content.hasClass('no_option')) {
do_something_else();
}
You can of course do the reverse test:
if(!main_content.hasClass('no_option')) ...

JQuery to add <body> class, need a little more help

I have this snippet of code to parse the URL and add a class to the <body>tag of my HTML page.
var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, " ");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace(" ","");
var newClass = pathSlashesReplacedNoFirstDash.replace(/(\.[\s\S]+)/ig, "");
$("body").attr("class",newClass);
if ( $("body").attr("class") == "")
{
$("body").addClass("class");
}
The issue I am having is that it deletes existing body classes already there. Instead, I would like to append to whatever body classes exist and not overwrite.
Use this:
$("body").addClass(newClass);
instead of
$("body").attr("class",newClass);
This is a setter: $("body").attr("class",newClass); which sets the class to the newClass and does not append it.
Use addClass instead of attr('class', newClass). The addClass also accepts a white-space separated list of class names, and correctly adds them.
$("body").addClass(newClass);
if ( $("body").attr("class") == "") // Makes no sense, since you have previously
{ // added `newClass`
$("body").addClass("class");
}
For documentation on addClass, see http://api.jquery.com/addClass/
.attr("class", newClass) is removing all existing classes. You should be using .addClass() instead:
$("body").addClass(newClass);
In addition, since you've just added a class to body, the code below will always be false:
if ( $("body").attr("class") == "") { }
Use addClass function instead - http://api.jquery.com/addClass/

JQuery, a new Selection using the results

Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?

Categories