JQuery get text in element but ignore style tags

I have javascript code that checks if a div has non-contextual text content.

This works, but it cannot distinguish between text content or style tag declarations in a div, and the test fails when there is no text content other than a style tag with css data.

The question is how to check for empty text content while ignoring a 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/

+4
source share
5 answers

One option is to clone an element and remove tags style:

$.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/

+3

, , each, HTML-, , HTML-. :

$('.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/

+3

Subtract style .

,

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

if($('#test2').text().trim().length - $('#test2 style').text().trim().length ==0){
    alert('test2 has no content!');
}

DEMO

+1

. .style1, style1? div, <div style="border: 1px;">, <head> HTML.

, <style> <head>.

0

javascript

document.getElementById('test2').innerText
0

All Articles