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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With