views:

48

answers:

1
$("br").parent().contents().each(function(i) {
   if(this.nodeType == "#Text")
    {
        alert(this.textContent);
    }
});

i am trying to select all texts not surrounded by html tags, but separated via <br>

doing this, sometimes returns a lot of alert messages, even when there should only be a couple.

i have tried to filter it out using

if(this.nodeValue != "") or if(this.textContent != "")

but still, empty alert messages pop up.

I suspect its the whitespaces in the html document (i dont control it). I only want to display this.textContent, which actually has visible text.

A: 

A text node's node type is 3, so:

$('br').parent().contents().each(function() {
    if ( this.nodeType == 3 ) {
      var text = (this.textContent ? this.textContent : this.innerText), temp = text.replace( /\s+/g, '')
        if ( temp.length ) {
            alert( text )
        }
    }
})

Live demo: http://jsbin.com/abalu

meder
i am getting text is undefined error. text = text.replace(/\s+/g, '')
Kim Jong Woo
Try my updated example. My prior one didn't account for br elements.
meder
If you want to strip the whitespace from alert, you could use .replace( /^\s+|\s+$/, '' ).
meder
thank you ! works beautifully.
Kim Jong Woo
Since you've established you have a text node, you should use `this.nodeValue` or `this.data` (which are equivalent for text nodes) rather than the non-standard `innerText` or `textContent`, which are designed to extract text content from elements.
Tim Down