0

I found How do I select text nodes with jQuery? but my problem is that although I can go like

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
  }).each(function() {
     this.nodeValue = //stuff
  });

I am trying to figure out how I can combine this.nodeType with the before and after nodes because some of the stuff I need can appear as a combination of the this.nodeValue + before, this.nodeValue or this.nodeValue + after if that makes sense and I need to test EACH node value as well as it in combination with the previous and next ?

Community
  • 1
  • 1
Andy
  • 18,723
  • 12
  • 46
  • 54

1 Answers1

0

If I understood correctly, you wanted to get the prev and next node when you hit the text node. See below,

var elContents = $('#test').contents();
elContents.each(function(idx, el) {
    if (el.nodeType == 3) {
        if (idx == 0) {
           prev = null;
           next = elContents.get(idx + 1);
        } else if (idx == elContents.length - 1) {
           prev = elContents.get(idx - 1);
           next = null;
        } else {
           next = elContents.get(idx + 1);
           prev = elContents.get(idx - 1);
        }

        //below is demo code
        $('#result').append ("<b>Prev: </b>" + $(prev).text() + " <b>Cur: </b>" + $(el).text() + "<b> Next: </b>" + $(next).text() + '<br />');
    }
});

DEMO: http://jsfiddle.net/SFmRR/

Note: In the demo, the elements inside div doesn't have any additional space/line breaks because when you iterate over contents() It includes line breaks and space as textNode.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134