Showing a div element dependent on if it has content - javascript

With jQuery I am trying to determine whether or not <div> has content in it or, if it does then I want do nothing, but if doesn't then I want to add display:none to it or .hide(). Below is what I have come up with,
if ($('#left-content:contains("")').length <= 0) {
$("#left-content").css({'display':'none'});
}
This does not work at all, if the div has not content then it just shows up anyway, can any offer any advice?

Just use the :empty filter in your selectors.
$('#left-content:empty').hide();

if( $( "#left-content" ).html().length == 0 ) {
$( "#left-content" ).hide();
}

try to remove first whitespaces:
// first remove whitespaces
// html objects content version:
var content = $.trim($("#left-content).html()).length;
if(content == 0) {
$("#left-content).hide();
}
// html RAW content version:
var content = $.trim($("#left-content).html()); // <-- same but without length
if(content == "") { // <-- this == ""
$("#left-content).hide();
}

Related

Input is not detecting that it is empty if removing text with "ctrl + a + backspace"

I am doing some easy div filtering with jQuery and input field. It is working, however it is not detecting that it is empty if I remove input using " Ctrl + a + backspace ", in other words if I select all text and remove it. What causes this?
It is not reordering divs back to default if using the keyboard commands but is going back to normal if you backspace every character.
This is how I do it:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
Your if block that handles the empty string is not showing the same elements that the else block hides. The else block calls .parent() but the if block does not.
So the else case shows or hides the parent of each .card element, but the if case shows the .card elements themselves—without unhiding their parents. See my comments added to the code (I also reformatted the conditional expression in the else for clarity):
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show all of the .card elements
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
// Show or hide the *parent* of this .card element
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
Since it sounds like the non-empty-string case is working correctly, it should just be a matter of adding .parent() in the if block so it matches the others:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show the parent of each .card element
$('.card').parent().show();
} else {
// Show or hide the parent of each .card element
$('.card').each(function() {
var text = $(this).text().toLowerCase();
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
This is the kind of situation where familiarity with your browser's debugging tools would pay off big time. The .show() or .hide() methods manipulate the DOM, and by using the DOM inspector you could easily see which elements are being hidden and shown.
In fact, as a learning exercise I recommend un-fixing the bug temporarily by going back to your original code, and then open the DOM inspector and see how it reveals the problem. While you're there, also try out the JavaScript debugger and other tools.
If you use Chrome, here's an introduction to the Chrome Developer Tools. Other browsers have similar tools and documentation for them.
It seems to be working just fine:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
console.log("input is empty");
} else {
console.log("input is not empty");
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="brandSearch">

regain html after emptying it using jquery?

I have an if/else loop inside my jQuery. I need to hide HTML on my text box inside my if portion and regain it at my else part. How can I do this using jQuery?
if (test == 1) {
$(#id).html(""); //code to hide html
} else {
//code to regain
}
code to hide html will works fine,but how to regain the code after emptying it?
you can't regain lost HTML unless you have saved it somewhere,
you can either show/hide the element
if(test==1){
$(#id).hide();
}
else{
$(#id).show();
}
or you can store the values somewhere in a variable
var html = "";
if (test == 1) {
html = $(#id).html();
$(#id).html( "" );
} else {
$(#id).html( html );
}
or set it to localstorage (if you browser supports it)
if (test == 1) {
localStorage.setItem("savedHTML", $(#id).html()) ;
$(#id).html( "" );
} else {
$(#id).html( localStorage.getItem( "savedHTML" ) );
}
You can assign the complete html inside your div to a variable.
var htmlContent = $(#id).html();
Then in your else, you can assign it back.
$(#id).html(htmlContent);

Utilizing jQuery Selectors to simplify HTML parser code

This code uses jQuery find() and several if statements to pick out certain text from an HTML document.
I'm trying to remove the if statements and interpret them to jQuery selectors in find(), at the very top line of code. Is this possible? If so, what would the selectors need to be?
$(document).find("a[href^='http://fakeURL.com/']").each(function()
{
var title = $(this).text();
var url = $(this).attr('href');
if(title.indexOf('Re: ') != 0)
{
if($(this).parent().attr('class') != 'quoteheader')
{
if(url.indexOf('topic') == 36)
{
if($(this).parent().attr('class') == 'middletext')
{
console.log(title);
}
}
}
}
});
For the last thing I left, you want to check if the topic is at index 36 ? not sure its possible via the selector, beside that everything went up to the selector (code not tested, should work tho)
$(document).find(".middletext:not(.quoteheader) > a[href^='http://fakeURL.com/']").each(function()
{
if(url.indexOf('topic') != 36)
return;
var title = $(this).text();
if(title.indexOf('Re: ') != 0)
return;
console.log(title);
});

hide parent div if link inside has empty href

I need to hide the buttonholder Div which is styled to look like a button. But the button styles images need to hide if the link itself is empty.
<div class="RegisterBtnHolder">
<span class="RegisterOrangeButton">
<span>
Register Online
</span>
</span>
</div>
I need to hide RegisterBtnHolder if the anchor tag has empty href or empty text..How do i do this in jquery.
give this a shot:
$(function(){
$("a[href=''],a:empty","div.RegisterBtnHolder").closest("div.RegisterBtnHolder").hide();
});
Using jQuery:
var button = $('.RegisterBtnHolder').find('a'); // caches the <a> element from the dom.
if(button.attr('href') == '') {
button.hide();
}
The above answer prolly works aswell, just remember try to avoid jumping into the DOM as much as possible, it will slow down your load time.
Fiddle
$('.RegisterBtnHolder a').each(function() {
if($(this).attr('href') === '' || $(this).text() === '') {
$(this).parents('.RegisterBtnHolder').hide();
}
});
Does this work for you:
if ($('div.RegisterBtnHolder a').text() == '' || $('div.RegisterBtnHolder a').attr('href') == '') $('div.RegisterBtnHolder a').hide()​
sample code below
if($("a").attr("href") === "" || $("a").text()===""){
$(this).closest("div").hide();
}
Useing filter() helps
http://api.jquery.com/filter/
$('.RegisterBtnHolder a').filter(function(){
/* add any additional tests you might need such as looking for "#" as an href*/
return $(this).attr('href')=='' || $.trim($(this).text())=='';
}).closest('.RegisterBtnHolder').hide();
JavaScript Only
var dilly = document.querySelectorAll('.RegisterBtnHolder a'), i;
for (i = 0; i < dilly.length; ++i) {
var $true = (dilly[i].getAttribute('href') == '')
if ($true == true) {
dilly[i].parentElement.style.display = 'none'
} else {
dilly[i].parentElement.style.border = "1px dotted silver"
}
}
jsfiddle

How do I check if an HTML element is empty using jQuery?

I'm trying to call a function only if an HTML element is empty, using jQuery.
Something like this:
if (isEmpty($('#element'))) {
// do something
}
if ($('#element').is(':empty')){
//do something
}
for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/
EDIT:
As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).
function isEmpty( el ){
return !$.trim(el.html())
}
if (isEmpty($('#element'))) {
// do something
}
You can also make it into a jQuery plugin, but you get the idea.
I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):
if($.trim($("selector").html())=='')
White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:
if ($someElement.children().length == 0){
someAction();
}
!elt.hasChildNodes()
Yes, I know, this is not jQuery, so you could use this:
!$(elt)[0].hasChildNodes()
Happy now?
jQuery.fn.doSomething = function() {
//return something with 'this'
};
$('selector:empty').doSomething();
If by "empty", you mean with no HTML content,
if($('#element').html() == "") {
//call function
}
In resume, there are many options to find out if an element is empty:
1- Using html:
if (!$.trim($('p#element').html())) {
// paragraph with id="element" is empty, your code goes here
}
2- Using text:
if (!$.trim($('p#element').text())) {
// paragraph with id="element" is empty, your code goes here
}
3- Using is(':empty'):
if ($('p#element').is(':empty')) {
// paragraph with id="element" is empty, your code goes here
}
4- Using length
if (!$('p#element').length){
// paragraph with id="element" is empty, your code goes here
}
In addiction if you are trying to find out if an input element is empty you can use val:
if (!$.trim($('input#element').val())) {
// input with id="element" is empty, your code goes here
}
Empty as in contains no text?
if (!$('#element').text().length) {
...
}
Another option that should require less "work" for the browser than html() or children():
function isEmpty( el ){
return !el.has('*').length;
}
You can try:
if($('selector').html().toString().replace(/ /g,'') == "") {
//code here
}
*Replace white spaces, just incase ;)
document.getElementById("id").innerHTML == "" || null
or
$("element").html() == "" || null
Vanilla javascript solution:
if(document.querySelector('#element:empty')) {
//element is empty
}
Keep in mind whitespaces will affect empty, but comments do not. For more info check MDN about empty pseudo-class.
if($("#element").html() === "")
{
}
Are you looking for jQuery.isEmptyObject() ?
http://api.jquery.com/jquery.isemptyobject/
Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289
$.extend($.expr[':'], {
trimmedEmpty: function(el) {
return !$.trim($(el).html());
}
});
JavaScript
var el= document.querySelector('body');
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));
function isEmptyTag(tag) {
return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
//return (tag.childElementCount !== 0) ? true : false ; // Not For IE
//return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
return (tag.children.length !== 0) ? true : false ; // Only Elements
}
try using any of this!
document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];
document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
​
Try this:
if (!$('#el').html()) {
...
}
Line breaks are considered as content to elements in FF.
<div>
</div>
<div></div>
Ex:
$("div:empty").text("Empty").css('background', '#ff0000');
In IE both divs are considered empty, in FF an Chrome only the last one is empty.
You can use the solution provided by #qwertymk
if(!/[\S]/.test($('#element').html())) { // for one element
alert('empty');
}
or
$('.elements').each(function(){ // for many elements
if(!/[\S]/.test($(this).html())) {
// is empty
}
})

Categories

Resources