Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get text in element but ignore style tags

I have javascript code that tests if a div has some non whitespace text content.

This works but it cannot differentiate between text content or style tag declarations within the div and the test fails when there is no text content but a style tag with css data.

Question is how to test for empty text content while ignoring the style tag?

HTML:

<div id='test1'>
    <div>   </div>
</div>

<div id='test2'>
    <div>   </div>

<style>
.style1{
    border:1px;    
}        
</style>    

</div>

Javascript:

// Works
if($('#test1').text().trim().length==0){
    alert('test1 has no content!');
}    

// Does not work due to style1 declaration within style tag within div
if($('#test2').text().trim().length==0){
    alert('test2 has no content!');
}    

Test URL: http://jsfiddle.net/sLDWB/

like image 475
zaf Avatar asked Mar 22 '23 00:03

zaf


2 Answers

One option is cloning the element and removing the style tags:

$.fn.isTextless = function() {
   var txt = this.first()
                 .clone()
                 .find('style')
                 .remove()
                 .end()
                 .text();

   return $.trim(txt).length === 0; 
}

if ( $('#test2').isTextless() ) {
    alert('test2 has no content!');
} 

http://jsfiddle.net/5Z3M4/

like image 86
undefined Avatar answered Apr 02 '23 03:04

undefined


You can just use a common class for all the elements you need to check, loop through them using each, store the initial HTML, remove the style tag, do your check and restore the initial HTML. Like so :

$('.testdiv').each(function() {
    var divHtml = $(this).html();
    $(this).find('style').remove();

    if($(this).text().trim().length==0){
        alert( $(this).attr('id') + ' has no content!');
    } 
    $(this).html(divHtml);
});

http://jsfiddle.net/sLDWB/1/

like image 24
Kaloyan Avatar answered Apr 02 '23 03:04

Kaloyan