zaf
zaf

Reputation: 23244

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/

Upvotes: 4

Views: 2118

Answers (5)

Ram
Ram

Reputation: 144689

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/

Upvotes: 4

Kaloyan
Kaloyan

Reputation: 7352

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/

Upvotes: 3

Kamlesh
Kamlesh

Reputation: 529

Use following javascript code

document.getElementById('test2').innerText

Upvotes: 0

mjkaufer
mjkaufer

Reputation: 4206

The style tag is meant to go in the head of a page. Why do you even have .style1 there if no element uses style1? If you want to change the style of a div, either do <div style="border: 1px;"> or make a style declaration in the <head> part of the HTML page.

In short, you shouldn't ever have a <style> tag outside of <head>.

Upvotes: -1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Subtract the style tag's length with the actual length.

Try,

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

Upvotes: 1

Related Questions