JQuery .hide...not hiding - javascript

This is probably a simple one but I can't seem to get it to work.
I have the following code:
<ul>
<li class='jSH'>Users: <span>0</span></li>
<li class='jSH'>Cars: <span>1</span></li>
</ul>
Essentially, I am trying to write a function that hides the li if the contents of span == 0. This is the jquery code but it doesn't work for some reason:
if ($('.jSH span').text() == "0")
$(this).closest('li').hide();
alert("should hide");
So, in this case, I get one alert for the first li (because the contents of span == 0), but the li does not hide.
Is there a problem with using 'this' in this case?
Thanks!

You would want to use .each since your current code returns multiple objects and their contents - .each will seperate them into a loop-like process where each individual element will be processed.
Fiddle:http://jsfiddle.net/fEEFq/
Javascript Code:
$('.jSH span').each(function(){
if ($(this).text() == "0"){
$(this).closest('li').hide();
alert("should hide");
}
});

Your problem is in $(this) - this, in the context of jQuery, only works when within a event callback (for example mouseover or click). You should fix that line to:
$('.jSH span').closest('li').hide();
Furthermore, you don't have {} around the body of the if statement. This will cause only the first statement after the if to be executed.

You can use $.filter
$('.jSH').filter(function() {
return $('span',this).text() == "0";
}).hide();

You're referring this to a conditional statement, which will not return your desired results.
Instead:
$('.jSH span').each(function(){
if ($(this).text() == "0"){ // now `this` is referring to every span in the jQuery collection
$(this).closest('li').hide();
}
});
http://api.jquery.com/each/

Related

executing function if siblings are not ":active"

How would one go about executing a function if an objects siblings do not have the pseudo class ":active" using jQuery? The reason for this question is that I would like to execute that function when the cursor is hovering the certain object and NONE of its siblings are ":active" (basic meaning: I want it to execute when the mouse is hovering the object and is not clicking down on any sibling).
To get the idea:
HTML:
<div class="tobehovered">...</div>
<div class="sibling">...</div>
...
JQuery:
function theOneToBeExecutedOnHover(){...}
$(".tobehovered").mouseenter(function(){
if( ... /* calculation???-ish */) theOneToBeExecutedOnHover();
}
The jQuery doesn't have to be formatted exactly that way. My example is just for principle.
From your hovered element $(this), find the siblings .siblings(), filter the active ones .filter(':active'), and check if you have none left .length === 0
That can be shortened like this:
if ($(this).siblings(':active').length === 0) {
Try this one
$(".tobehovered").mouseenter(function(event){
if(event.target.className == 'active'){
return;
}
//here execute function
}

Use array to show elements

I've got a problem that I can't figure out and was wondering if you good people could help out? I'm building a filter system that uses data options on the tags.
The nav elements add to an array when pressed and take that option out
of the array when pressed again.
You may notice that the first set allows for combination and the date range doesn't. This is intentional. My problem lies with asking the script to show the elements in the #container that match the data tag when pressed - I want to show the li elements within #container that match the data-season="" or the data-date="".
in the seasons script this is my problematic piece of script....
if (typeof $("#container li").data('season' == showseason ) )
{
$(this).show();
}
I've tried various ways but I'm now just going in loops getting more confused with each attempt. HELP :)
Jsfiddle Demo
You should change that if statement. remove the typeof keyword, and compare the data value.
if ($("#container li").data('season') == showseason )
{
// do something here
}
Or better yet, iterate through each of the li within #container and get the data-season value.
$("#container li").each(function(){
var season = $(this).data("season");
if(season == showseason)
$(this).show();
else
$(this).hide();
});
Please refer to the updated fiddle: http://jsfiddle.net/b2eh2w07/11/

jQuery if div has no any class or div

There is a duplicated <div class="content" data-num="2"></div> (would be more if click the button more times)which has got nothing in it.
How to check if content has nothing in it and get it removed ?
if($('.content').children().length == 0)
or need to use each something like?
$('.content').each(function(i, obj){
if($('.content').children().length == 0){
$(this).remove();
}
});
You can use the :empty jQuery selector which will select all elements that have no children. See http://api.jquery.com/empty-selector/ for details.
Using :empty will prevent the need for extra if checks in your loop - your delete function only operates on the items to delete ... much more efficient.
So something similar to:
$('.content:empty').each(function() {
//Do your delete, etc here :)
$(this).remove();
});
As suggested by jfriend00, the further simplification to just do a delete would be:
$('.content:empty').remove();
Lots of different ways to tackle it.
There is probably a simpler way to do this, but checking the html() of each .content should work for you. Demo
$(".content").each(function(i, obj) {
if($(this).html() == '') {
$(this).remove();
}
});
You've an extra ) which accidentally closing your if clause:
if($('.content')).children().length == 0){
// ------------ ^ remove this
Otherwise, your code with each() should work.

Check if element is a div

How do I check if $(this) is a div, ul or blockquote?
For example:
if ($(this) is a div) {
alert('its a div!');
} else {
alert('its not a div! some other stuff');
}
Something like this:
if(this.tagName == 'DIV') {
alert("It's a div!");
} else {
alert("It's not a div! [some other stuff]");
}
Solutions without jQuery are already posted, so I'll post solution using jQuery
$(this).is("div,ul,blockquote")
Without jQuery you can say this.tagName === 'DIV'
Keep in mind that the 'N' in tagName is uppercase.
Or, with more tags:
/DIV|UL|BLOCKQUOTE/.test(this.tagName)
To check if this element is DIV
if (this instanceof HTMLDivElement) {
alert('this is a div');
}
Same for HTMLUListElement for UL,
HTMLQuoteElement for blockquote
if(this.tagName.toLowerCase() == "div"){
//it's a div
} else {
//it's not a div
}
edit: while I was writing, a lot of answers were given, sorry for doublure
Going through jQuery you can use $(this).is('div'):
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
Some of these solutions are going a bit overboard. All you need is tagName from regular old JavaScript. You don't really get any benefit from re-wrapping the whole thing in jQuery again, and especially running some of the more powerful functions in the library to check the tag name. If you want to test it on this page, here's an example.
$("body > *").each(function() {
if (this.tagName === "DIV") {
alert("Yeah, this is a div");
} else {
alert("Bummer, this isn't");
}
});
let myElement =document.getElementById("myElementId");
if(myElement.tagName =="DIV"){
alert("is a div");
}else{
alert("is not a div");
}
/*What ever you may need to know the type write it in capitalised letters "OPTIO" ,"PARAGRAPH", "SPAN" AND whatever */
I'm enhancing the answer of Andreq Frenkel, just wanted to add some and it became too lengthy so gone here...
Thinking about CustomElements extending the existing ones and still being able to check if an element is, say, input, makes me think that instanceof is the best solution for this problem.
One should be aware though, that instanceof uses referential equality, so HTMLDivElement of a parent window will not be the same as the one of its iframe (or shadow DOM's etc).
To handle that case, one should use checked element's own window's classes, something like:
element instanceof element.ownerDocument.defaultView.HTMLDivElement
Old question but since none of the answers mentions this, a modern alternative, without jquery, could be just using a CSS selector and Element.matches()
element.matches('div, ul, blockquote');
Try using tagName

If statement fails with $(this), but works with absolute

I ran into this very odd scenario.
This won't hide the H1:
if ($('#content h1').hasClass('active')) {
$(this).hide();
}
Only this will:
if ($('#content h1').hasClass('active')) {
$('#content h1').hide();
}
Why can't I use the (this)? Is something wrong with the script?
That is the correct behaviour. In the context of your if statement this does not hold a reference to your h1 element but to the document element (or function if you are inside of a function).
You could do:
$('#content h1').foreach(function() {
if (!$(this).hasClass('active')) {
$(this).hide();
}
});
In this case, as Jan explained, this will be in the context you expect it to be (the heading element).
What you want is probably
var h1 = $('#content h1')
if (h1).hasClass('active')) {
h1.hide();
}
your "this" will, as stated above, not reference your object.
The statement $('#content h1').hasClass('active') returns a Boolean value (true or false), as opposed to a jQuery object, which is what you're trying to use $(this) for. See the usage of hasClass here.
If you're trying to perform an action on all elements that match a certain selector, give this selector a try instead:
$("#content h1.active").hide();
This finds all elements with an id attribute of "content" that contain an h1 element with a class attribute of "active," and hides them all.

Categories

Resources