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

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
}
})

Related

How to make an input restriction function using jquery

I want to do is put a character and length restriction in an input using this rules:
A combination of at least ten numbers, letters and punctuation marks
(like ! and &)
and if the user didnt complete the rules the input value will be back to empty again.
My problem is I'm still a beginner and my current code wont work as i wanted. Can anyone help me with this please.
Current output: http://jsfiddle.net/5kcsn/271/
Script:
$(document).ready(function () {
$('#example').on('blur', function () {
$('#example').change(inputVerify);
inputVerify()
})
$('#example').on('keydown', function () {
$('#example').change(inputVerify);
inputVerify()
})
$('#example').change(inputVerify);
function inputVerify(value) {
return /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value) && /[a-z]/.test(value) && /\d/.test(value)
};
});
I don't want to tell you "how to do it better in general", but what about giving live feedback instead of reverting a bad entry? This way the user can a) see as soon as it is correct, b) correct his former entry:
$("#example").on('keydown',function(){
if(!inputVerify($("#example").val())){
$("#example").css("border","1px solid red");
} else {
$("#example").css("border","1px solid black");
}
});
function inputVerify(value){
return /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value)
&& /[a-z]/.test(value)
&& /\d/.test(value)
};
You should really do this only on blur, it should look something like this:
$(document).ready(function(){
$('#example').on('blur', function(){
if( !inputVerify() ) {
$(this).val('');
}
});
});
function inputVerify(value){
return /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value)
&& /[a-z]/.test(value)
&& /\d/.test(value)
};
You see, your inputVerify function returns true or false and you would have to remove the input yourself by $(this).val('');.
The jsFiddle: http://jsfiddle.net/5kcsn/272/
Please note that I have not tested your regex, as I am not too familiar with them, yours seem to work though.
Try this, note I did not check your regular expression:
$(document).ready(function () {
$('#example').keydown(inputVerify);
function inputVerify(event) {
var value = $(this).val();
if (!(/^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value)
&& /[a-z]/.test(value)
&& /\d/.test(value))) {
$(this).val('');
}
};
});
Link to JSFiddle
The function inputVerify catches the event passed by the keydown handler and uses the $(this) which refers to the element the event is triggered on to get the value of the input.
And then, if the regex tests fail, empty the input.

What is the best way cross-browser to trim an element innerHTML?

What is the best way cross-browser to trim an element innerHTML?
jsFiddle: http://jsfiddle.net/6hk8z/
I am assuming you are getting confused with the html code that is not whitespace but merely rendered as such by the browser. See customised implementation below:
String.prototype.trimmed = function(){
return this.replace(
/^(\s| |<br\s*\/?>)+?|(\s| |<br\s*\/?>)+?$/ig, ' '
).trim();
}
updated jsFiddle
Use the DOM, not innerHTML which you would need to parse.
function trimContents(element) {
function iterate(start, sibling, reg) {
for(var next, c = element[start]; c != null; c=next) {
next = c[sibling];
if (c.nodeType == 1 && c.nodeName.toLowerCase() == "br"
|| c.nodeType == 3 && !(c.nodeValue = c.nodeValue.replace(reg, "")))
element.removeChild(c);
else
break;
}
}
iterate("firstChild", "nextSibling", /^\s+/);
iterate("lastChild", "previousSibling", /\s+$/);
}
(demo at jsfiddle.net)
Have you tried jQuery's $.trim()? See jQuery documentation for more details.

How to match two html elements

For example, I have
<div class="welcome_font">name</div>
and
<div id="nameho" style="color:#5AC7E6;">another-name</div>
I want to write an "if" statement in jquery/javascript where if "name" matches "another-name", then do something. How do I do that?
The .html() function grabs the inner html when using jQuery. So you could use the following to compare the two:
if ( $('.welcome_font a').first().html() === $('#nameho').html() )
{
...
}
let me know if that makes sense or if you have any questions :)
Try,
if( $('.welcome_font a').text() == $('#nameho').text() )
{
////Do something
}
Research first next time. You could get this with a simple search.
if($(".welcome_font a").text() == $("#nameho").text())
{
//To do
}
var name_1 = $('.welcome_font').text();
var name_2 = $('#nameho').text();
if(name_1===name_2) {
alert('yes');
} else {
alert('no');
}
Demo : http://jsfiddle.net/TSGqC/
or
var name_check = ($('.welcome_font').text()===$('#nameho').text()?true:false);
if(name_check) {
alert('yes');
}
Demo : http://jsfiddle.net/TSGqC/1/

Javascript loop with dynamic jquery val() not being picked up

I'm trying to pick out the value of an input box using jquery.
No probs there
$('#id_of_my_input_box_1').val();
But I need several so decided to put them into a loop:
============
var config_total_instances = '==some value='
for (var x = 1; x <= config_total_instances; x++) {
if (isset($('#id_of_my_input_box_'+x).val())) {
alert($('#id_of_my_input_box_'+x).val());
}
}
============
If I submit the form and I've got say 10 input boxes, the code above doesn't alert a value if the relevant input box has value.
I'm using a function below to check for values.
============
function isset(my_variable) {
if (my_variable == null || my_variable == '' || my_variable == undefined)
return false;
else
return true;
}
============
Am I missing something vital..? :-(
Addition: I shoudl add that I'm askign why I don't get the value of
$('#id_of_my_input_box_'+x).val()
echoed out in my alert box
Extending #Faber75's answer. You can set a class name for all your text element and then use something like this
$("input:text.clsname").each(function(){
if (isset(this.value)) {
alert(this.value);
}
});
In your current code if you are assigning a string to config_total_instances then it will not work.
don't consider my message an answer, more of a tip.
For a simplier code you could consider adding a class to the textboxes you need to check.
For example adding to all the inputs you need to check the class="sample" you could the use the jquery selector $(".sample") , returning you all the items and then you could simply do
$(".sample").length to count the items and $(".sample")[0].val() (or similar) to get/test values.
Cheers
Have you tried this? (note that there are three =)
if (my_variable === null || my_variable == '' || my_variable === undefined)
As an alternative to this try
if (typeof(my_variable) == 'null' || my_variable == '' || typeof(my_variable) == 'undefined')
Maybe I'm misunderstanding, but can't you just get all the <input>'s in a <form> that aren't :empty if that's the end goal of what you're trying to accomplish?
$('form#some_id input:not(:empty)').each(function () {
// do something with $(this).val() now that you have
// all the non-empty <input> boxes?
});
Or if you're just trying to tell if the user left some <input> blank, something like:
$('form#some_id').submit(function (e) {
if ($(this).find('input[type="radio"]:not(:checked), input[type="text"][value=""], select:not(:selected), textarea:empty').length > 0) {
e.preventDefault(); // stops the form from posting, do whatever else you want
}
});
http://api.jquery.com/category/selectors/form-selectors/

Showing a div element dependent on if it has content

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();
}

Categories

Resources