You can do like if($('.div').find('.someelem').length == 0 .. to check whether .someelem is available inside the div,
but what if I want to check for any element? I don't know what is the class within.
<div>
</div>
^ Check above div contain something or not.
A faster way to do it is using .find() cause it will not trigger the somewhat expensive jQuery's Sizzle Selector Library:
if( !$(".div").find(">")[0] ){
// Maybe has text, but has absolutely no children Elements.
}
If you want to be more specific about your selectors, instead of using ">" (any immediate child) you can use "div" aswell, to restrict your search to DIV Elements only.
You can also check with "if is empty"
$(".div:empty").someMethodYouWant(); // Do some stuff on empty elements. (Really empty)
or
if( $(".div").is(":empty") ){
// Has no elements and no text
}
note that the above will yield false if you have just some text (means it's not empty).
If you rather want to go for immediate children > elements
if( !$(".div:has(>)").length ){
// Maybe has text, but has absolutely no children Elements.
}
or also:
if( !$(".div:has(>)")[0] ){
// Maybe has text, but has absolutely no children Elements.
}
or even simpler:
if( !$(".div >")[0] ){
// Maybe has text, but has absolutely no children Elements.
}
Related
I have the below code that checks to see if any of my divs has the class "wrong" and if so it shows the jQuery UI dialog box. However i want to extend the code so that it checks those divs and if there are any that are empty it should not show the dialog box.
I've looked around and some people are suggesting using children().length > 0 to accomplish this, but I'm not sure how to write this with my code.
js:
$("#run").click(function() {
if ($("[id^='Drop']").hasClass("wrong")) {
$("#dialog1").dialog("open");
}
});
The following selectors could be used to test if an element is empty or not:
:empty matches elements that have no children (thus, empty)+
:parent matches elements that have children+
Now, rephrasing your statement:
... so that it checks those wrong divs and if
there are any that are empty they are all full it should
not show the dialog box.
You would write:
var $allWrong = $("id[^='Drop'].wrong"),
$notEmpty = $wrong.filter(":parent");
if ($allWrong.length && $allWrong === $notEmpty) {
// show dialog
}
+ Text nodes are counted when counting children. <span> </span> contains a text node which contains a whitespace. Therefore it matches :parent and does not match :empty.
The logic consists of two parts:
Finding elements with id property starting with "Drop" and having the .wrong class.
Checking whether any of those elements are empty.
To do this, I'm saving the first step in an intermediate variable, before doing the final condition:
var $wrongFields = $('[id^="Drop"].wrong');
if ($wrongFields.length && !$wrongFields.filter(':empty').length) {
// at least one field exists with:
// - id starting with "Drop"
// - class of "wrong"
// and none of those fields are empty
$("#dialog1").dialog("open");
}
Demo
This would also work
$("#run").click(function(){
if ($("[id^='Drop']").hasClass("wrong") && $("[id^='Drop'].wrong:empty").length ) {
$( "#dialog1" ).dialog( "open" );
}
});
I need jquery to get the closest id,once the the image is visible.
this is my query so far
(...)
if(isonscreen)
{
//this works, but I need it to find only images inside the content-bubble div tag
// and of course this grabs any image no matter what div the image is inside of
console.log($(this).closest('img').attr('id'));
}
(...)
<div class="content-bubble">
<h2>{{imageTitle}}</h2>
<img src="loading.gif" id="lazyload{{imgId}}" class="content-bubble-img"">
</div>
I've tried this but its not working and returns undefined
console.log($(this).closest('.content-bubble-img').find('img').attr('id'));
console.log($('.content-bubble-img').closest('img').attr('id'));
I thing you want the function find(), not closest().
closest finds the nearest parent of an element, while find().filter(':first') finds the first children inside an element. Or to say it with the doc's words:
closest:
For each element in the set, get the first element that matches the
selector by testing the element itself and traversing up through its
ancestors in the DOM tree.
find:
Get the descendants of each element in the current set of matched
elements, filtered by a selector, jQuery object, or element.
http://api.jquery.com/closest/
http://api.jquery.com/find/
To comment your code:
console.log($(this).closest('img').attr('id'));
This is actually pretty bad since images cant have children, this does only work since closest() returns the selected element itself which is the image when you use $(image).closest(). Replace closest with find and you're good to go.
If u have to find all images inside "content-bubble div" no matter what div the image is inside of then use this :
$('.content-bubble img');
First of all it would be much easier to fully understand what you're trying to achieve if you have added a fiddle of it.
Nevertheless I'm guessing that you're checking whether an image is currently visible - which means that in this piece of code
(...)
if(isonscreen)
{
console.log($(this).closest('img').attr('id'));
}
(...)
$(this) actually refers to the image you're interested in - thus you might want to simply retrieve its id attribute with $(this).attr('id')
Since you want to limit it to images which are placed in divs with a specific class, you might just want to check if one of its parents has class '.content-bubble', by
$(this).parents('.content-bubble').length
You may also use closest, since it actually traverses up the DOM tree from the element you specified, and:
if($(this).closest('.content-bubble').length)
which in this case would return true when $(this) or any of its parent has class .content-bubble
I'm using the espy plugin for jquery
This is how you find the id of the nearest image inside a div tag
once the image is visible
$('.content-bubble-img').espy(function (entered, state) {
if (entered)
{
// element entered the viewport
// state === 'inside'
console.log('element entered viewport');
console.log($(this).closest('img').attr('id'));
}
else
{
// element left the viewport
if (state === 'up')
{
// element is now above the trigger area
console.log('element left the viewport');
}
else if (state === 'down')
{
// element is now below the trigger area
console.log('element below the trigger area');
}
}
});
I have a few input fields that I'm trying to add a class to their parent container if they are not empty.
Here's the CoffeeScript:
$(".inputA, .inputB").parent().addClass(->
if !$(this).is(":empty")
"input-set"
)
This is successfully appending "input-set" to the parent class, but in all cases, not just empty input fields.
:(
Use jQuery.filter()
$(".inputA, .inputB").filter(function(){
return this.value !='';
}).parent().addClass("input-set");
Less function calls than using $.each
:empty will select elements that don't have children. Therefore, using it to conditionally select the parents of certain elements doesn't make any sense.
ref: https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
If you're looking to add the class to the parents of inputs that haven't been populated then you could use something like:
$(".inputA, .inputB").each(function(){
if (this.value !== "") {
$(this).parent().addClass('input-set');
}
});
First, input elements are by definition empty..
Read the :empty documentation at http://api.jquery.com/empty-selector/
Second you are testing the parent elements and not the input ones.. (and since they are parents, meaning they are not empty they all fit the bill..)
What is the best way in your experience to detect the existence of an element inside a div?
I'm currently using this:
if (($('.parentDiv').width()) > 0){
//Do something
}
There has to be a more elegant way.
If empty means not even text nodes:
if ($('.parentDiv').contents().length){
//Do stuff
}
or:
$('.parentDiv:not(:empty)') // which is nice...
.contents docs:
Description: Get the children of each element in the set of matched elements, including text and comment nodes.
if you care only of elements and not text nodes:
if ($('.parentDiv').children().length){
//Do stuff
}
Probably not what you want, but considering there's at least a little confusing over your requirements, you could consider if anything at all is within the container: elements, text, whatever.
Say you have an empty div:
<div class="parentDiv"></div>
Then $(".parentDiv").html().length == 0 indicates its emptiness.
If the div is not empty:
<div class="parentDiv"> </div>
<div class="parentDiv"><div></div></div>
Then $(".parentDiv").html().length will indicate its occupiedness (returning 1 and 11, respectively, in those scenarios.)
If you wish to check only for elements, or specific elements, then $(".parentDiv").children() would be the way to go.
Assuming you only care about elements (and not text nodes), you could check to see if the element has any children:
if($('.parentDiv').children().length) {
//Do stuff
}
Use the children() function
$('.parentDiv').children()
if ( $( '.parentDiv' ).children().length > 0 )
{
// do something
}
I've just started using jQuery, and can't get my head around this.
I need to check if a div contains anything but a h3 header tag.
The structure of the html is as follows:
<div id="myContainer">
<h3>A header that is always present</h3>
any html, plain text or empty
</div>
Here's the jQuery:
if ( $("#myContainer h3:only-child") ) {
$("#myContainer").css("display", "none");
}
The above will simply hide the div if there is no other html elements present, which is not what I intend since it will also contain plain text. I have tried with other selectors and functions, but I just can't seem to get it right.
Thanks in advance :)
I think you want a function which will tell you if the div contains just H3 or also has other elements. I don't think there is a direct jQuery selector for that, so I wrote a simple function to checkForJustH3.
DEMO - That shows how to hide div that just has H3.
Check out the below demo by editing the div contents and Hit Run to see the result.
DEMO
function containsJustH3 (el) {
var result = true;
$(el).contents().each (function() {
if (this.nodeName != 'H3') {
//check for blank line or empty spaces
if (this.nodeType == 3 && $.trim(this.nodeValue) == '') {
return true;
}
result = false;
return false;
}
});
return result;
}
And using the above function you can do something like,
if ( containsJustH3("#myContainer") ) {
$("#myContainer").css("display", "none");
}
Try:
$("#myContainer").children('h3').hide();
jsfiddle
You can wrap the 'plain text' in a p element and use this selector:
fiddle
$("#myContainer").children().not('h3').hide();
//Select all children but not the h3
HTML:
<div id="myContainer">
<h3>A header that is always present</h3>
<p>any html, plain text or empty</p>
</div>
You can use the length property to see how many children the div has
$("#myContainer").children('h3').length
The fundamental problem here is that jQuery methods like children will not get text nodes. If you want to see how many children a div has, and include the text nodes, you'll want to grab the actual dom node, and check the length of its childNodes property. This will include text nodes.
if ($("#myContainer")[0].childNodes.length > 1) {
var $cont=$('#myContainer'), $children=$cont.contents().not('h3');
if( ! $children.length) {
$cont.hide();
}
Using contents() method will check if there are tags or text nodes in element, check if the children object has length, if not hide the container
You can use $("#myContainer").contents().length to get the number of nodes, including text nodes. However, this includes the newline before the <h3>, etc.