Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery selector for a empty div

How select a empty divs and divs with only one space character, ej:

Ej: A jquery rule selector that select this:

<div class="thumbnails"></div>
<div class="thumbnails"> </div>

but that NOT select this:

<div class="thumbnails">Lorem ipsum amet</div>

I tried this

$('.thumbnails:empty').css('background-color', "#f0f");

and works fine with:

<div class="thumbnails"></div>

but does not select this case (note space character):

<div class="thumbnails"> </div>

Test: http://jsbin.com/ozohak/1/edit

like image 449
karacas Avatar asked Jan 07 '13 15:01

karacas


People also ask

How do you check if a div is empty or not in jQuery?

Method 1: Using the “:empty” selector: The element to be checked using is() method. The is() method is used to check if one of the selected elements matches to the selector element. This method can be used on this element to test if it is empty by using “:empty” selector.

How do I check if a div is not empty?

Use the childNodes property to check if a div element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments. If the property returns a value of 0 , then the div is empty.

How do I empty a div?

To clear the contents of a div element, set the element's textContent property to an empty string, e.g. div. textContent = '' . Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value.

Is Empty jQuery?

jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.


1 Answers

Use the filter function to detect elements with no text

$('.thumbnails').filter(function(i,v){
    return $.trim($(v).text()).length == 0;
}).css('background-color', "#f0f");

http://jsbin.com/ozohak/5/edit

EDIT:

You can select empty elements and one space using the filter function also if that is your requirement

$('.thumbnails').filter(function(i,v){
    return $(v).text() == '' || $(v).text() == ' ';
}).css('background-color', "#f0f");

http://jsbin.com/ozohak/10/edit

like image 126
wirey00 Avatar answered Oct 24 '22 23:10

wirey00