jQuery check if exists using empty element - javascript

Is it possible to check if an element exists in jQuery using the length function, even though the element is empty?
I have an empty div <div id="myDiv"></div> that gets populated by AJAX when the user scrolls to a certain point on the screen, but when I try targeting the div before that point I'm getting nothing. The code I'm using is…
if( jQuery('#myDiv').length) {
alert('#myDiv exists!');
} else {
alert('#myDiv doesn\'t exist!');
}
but I'm wondering if the reason it isn't selecting the div is because it's empty. Does that matter when using the length function?

.length is not a method. It is a property, so remove the () after it.
if( jQuery('#myDiv').length ) {
// If the div exists do this
} else {
// If it doesn't do this
}

length is a `property` and not a `function`. It should be
if( jQuery('#myDiv').length) {
alert('#myDiv exists!');
} else {
alert('#myDiv doesn\'t exist!');
}
It should be the below codes assuming you want to check whether the div is empty or not
if( jQuery('#myDiv').html().length > 0){
// If the div is empty do this
}
else{
// If its not empty do this
}
Check the jQuery DOCS
EDIT:
Check if you have used the if condition inside document ready. Check out the fiddle
jQuery('#myDiv').html().length > 0
Here is the Fiddle Link

Related

remove div if empty or appendChild

I need that when my div is empty, remove if not, run the appendChild code. I'm not getting the logic right, I think
$(window).on("load", function() {
if ('#leftmenu:empty') {
$('#leftmenu:empty').remove();
} else {
document.querySelector('.iframe-output').appendChild(
document.querySelector('.paddingbox iframe')
}
});
$(window).on("load", function() {
if ($('#leftmenu').html().length == 0) {
$('#leftmenu').remove();
} else {
//do whatever
}
});
I don't know what you want. Please refer enter link description here to find how to check div is empty. Then if not you can add the code you want. Currently, this code is the wrong syntax. You need to fix it like
document.querySelector('.iframe-output').appendChild(
document.querySelector('.paddingbox iframe'));
$( "p:empty" )
//.text( "Was empty!" )
//.css( "margin", "0" )
.remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Has text</p>
<p></p>
<p></p>
<p>Has text</p>
Please Try this
$(document).ready(function() {
if ($('#leftmenu').length==0)
{
$('#leftmenu').remove();
} else {
document.querySelector('.iframe-output').appendChild(
document.querySelector('.paddingbox iframe')
}
});
You've got a couple of errors with your code - you're if statement is only checking a string and not actually if the empty div exists and you have a syntax error on your append (and I'm not sure you can append directly to a collection like that)
Try this (comments to what I have changed)
$(window).on("load", function() {
var $emptyDiv = $('#leftmenu:empty'); // get empty div
if ($emptyDiv.length) { // see if empty div exists
$emptyDiv.remove(); // remove empty div
} else {
$'.iframe-output').append($('.paddingbox iframe')); // you may as well use jquery append as you are using jquery
}
});
:

jQuery get sibling using next() returns undefined

How do you use jQuery's next() method to get the contents of an element's sibling? I am trying to get text associated with a google search result. To this end, I stored links in a variable with $('h3.r a'). Next I added a click handler, which would trigger the code that grabs the page description underneath the link. I expected $(this).next().html() to get contents of the next sibling in the same manner $(this).html() worked. Unfortunately, I was mistaken. Here is the jQuery, any help is really valued
links.click(function() {
var nextElement = $(this).next()
console.log(nextElement.html()) //why doesn't this get contents?
var d = $(this).nextElementSibling
console.log(d)
})
EDIT: so I checked the console and when I logged $(this) I got
{
"0":{
"jQuery311027308429302958161":{
"events":{
"click":[
{
"type":"click",
"origType":"click",
"data":null,
"guid":1,
"namespace":""
}
]
}
}
},
"length":1
}
When I logged $(this).next()
{
"length":0,
"prevObject":{
"0":{
"jQuery311027308429302958161":{
"events":{
"click":[
{
"type":"click",
"origType":"click",
"data":null,
"guid":1,
"namespace":""
}
]
}
}
},
"length":1
}
}
Use this.nextSibling to select next #text node, .textContent to select text of node.

What's the proper way to check if an element has an ID or not with jQuery?

I thought I could check if an element has an ID with has() like this:
if ($button.has('#Menu-Icon')[0] !== undefined) {
//do stuff
}
but I learned that instead, it checks if there's a descendant which matches the ID. So I don't think this is the right jQuery method to use, but nevertheless it's the only thing that seems to show up when I search the subject on Google.
Which jQuery method is the right one for checking if a given element has a certain ID or not?
Check the id using the attr() function like this:
$('button').on('click', function() {
if ($(this).attr('id') == 'TheID') {
alert('The button you pressed has the id: "TheID"!');
} else {
alert('You pressed a button with another id..');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="TheID">TheID</button>
<button id="anotherID">anotherID</button>
You can check the id property like of the underlying element like
if ($button[0].id == 'Menu-Icon') {
//do stuff
}
or jQuery way to use .is()
if ($button.is('#Menu-Icon')) {
//do stuff
}
The has() method is used to filter a set of elements by checking whether those contains elements matching the passed selector, also it returns a jQuery object so checking for undefined will never be true
Try something like below which should work:
<div id=""></div>
$(document).ready(function(){
if($('div').attr('id') != ''){
alert("have id");
}else{
alert("do not have id")
}
});

How to hide a div map if "p" tag is empty

I need to hide a div (.map_toogle) if a p-tag contains 'I have no Map', otherwise (p-tag is empty) I want to visible that div (.map_toogle).
I have following code but it always hide that div if p-tag is empty.
$(document).ready(function () {
if($(".right_block p:contains('I have no Map')")) {
$('.map_icon').hide();
}
if($(".right_block p:contains('I have no Map')")) {
$('.map_toogle').hide();
}
if($(".right_block p:contains('I have no Map')")) {
$('#camera_wrap_2').show();
}
if($('.right_block > p').is(':empty')) {
$('.map_toogle').css("display", "block");
}
if($('.right_block > p').is(':empty')) {
$('.map_toogle').css("display", "block");
}
});
Why not:
$(".right_block p").text()!== 'I have no Map' ? $(".map_toggle").show() : $(".map_toggle").hide();
This is a simple if/else statement testing on whether the text within the p explicitly matches the string 'I have no Map' and showing/hiding the map div as a result.
That said, you may want to expand this into a regular full-fat statement as it looks like you're also performing a few other actions:
if($(".right_block p").text()!== 'I have no Map'){
$(".map_toggle").show();
// other actions...
}else{
$(".map_toggle").hide();
// other actions...
}
However..
Generally it is best to code in as accommodating way as possible, what if you change the text indicating there is no map? As such, it may be better to test for the inverse (as long as you know this will be no text at all), and use:
if($(".right_block p").text()){ // ....no text present
You have multiple if checks while you can reduce it this way and check for the length:
$(document).ready(function () {
if($(".right_block p:contains('I have no Map')").length !== 0) {
$('.map_icon, .map_toogle').hide();
$('#camera_wrap_2').show();
}
if($('.right_block > p').text().trim() === '') {
$('.map_toogle').css("display", "block");
}
});
This will do the trick
if($('.right_block p').text()==="I have no Map") {
$('.map_icon').hide();
} else {
$('.map_icon').show();
}
You need to fetch the content using .text() which will return you the text

How can I make an element appear and disappear using Jquery.

I want to do something like this:
$(document).ready(function(){
if($('.undermenu').css('display','block')){
$('#menu').click(function(){
$('.undermenu').css('display','none');
});
}
else{
$('#menu').click(function(){
$('.undermenu').css('display','block');
});
}
});
This code does not work, but is there any Jquery "effect" or whatever that I can use to hide/un-hide.
For example is there and way to check whether or not display is set to none or block?
Thanks.
Just use toggle():
$('#menu').click(function() {
$('.undermenu').toggle();
});
Though the reason your if($('.undermenu').css('display','block')) didn't work is because you set the display property of the element(s) to block, rather than getting the display property and testing it, which would be:
if ($('.undermenu').css('display') =='block')
If you really want to use an if to test the current display, before modifying the presentation, you'd have to do it inside of the click handler (otherwise it will only run once, on DOMReady, rather than every time):
$('#menu').click(function(){
if ($('.undermenu').css('display') == 'block') {
$('.undermenu').hide();
}
else {
$('.undermenu').show();
}
});
Or, if you want to risk the wrath of your colleagues, you can jazz that up a little:
$('#menu').click(function(){
var undermenu = $('.undermenu');
undermenu[undermenu.css('display') == 'block' ? 'hide' : 'show']();
});
References:
css().
toggle().
You use a setter on your condition :
// This line update .undermenu to display it and return true (return $('.undermenu'), so true)
if($('.undermenu').css('display','block')){
But you must get the value, and test
if($('.undermenu').css('display') === 'block'){
And you code conception is bad. If you do that, you test on document are ready if the .undermenu are displayed or not, and you put a function to the click trigger (to display or to hide..) but ! when your .undermenu was change, you already have the same trigger (to display or hide, and he never change)..
So you need to put your trigger for each click and test the value (displayed or not) on the trigger :
$(document).ready(function(){
$('#menu').click(function(){
if($('.undermenu').css('display') === 'block'){
$('.undermenu').hide();
}
else {
$('.undermenu').show();
}
});
});
On jquery exists:
$("#element_id").show();
$("#element_id").hide();
also you can use:
$("#element_id").fadeIn();
$("#element_id").fadeOut();
This show and hide elements with fade effects.
You can query if the element is hidden:
if($("#element_id").is(":hidden")){
$("#element_id").show():
}
else{
$("#element_id").hide();
}
What you're looking for is .toggle()
$("div").click(function () {
$("img").toggle("slow", function () {
// Animation complete.
});
});
Here is a fiddle: http://jsfiddle.net/FQj89/
You can put the if statement in the function so you don't repeat yourself. You can probably also use toggle(); type stuff depending on what you are doing. ---
$('#menu').click(function(){
if ( $('.undermenu').is(':visible') ) {
$('.undermenu').hide();
else {
$('.undermenu').show();
}
});
This is a good way too, depending on what you are doing though, one may be better than the other.
if ( $('.undermenu').css('display') === 'block' ) { // do something }

Categories

Resources