views:

48

answers:

2

Here's some example code:

<input type="checkbox" id="send-notice" name="send-notice" value="1" /> This is a notice to all users.  

<label for="subject">Subject</label>

I want to be able to select the text "This is a notice to all users." so I can remove it.

I'm not sure how to do so though.

I've tried using jQuery('#send-notice').next(), but that selects the <label for="subject"> block.

I also tried wrapping a <div> around the text using jQuery('#send-notice').after() and a closing </div> tag on jQuery("label[for='subject']").before(). But jQuery doesn't like unopened elements.

Any help here?

+1  A: 

jQuery won't be of too much help here, since its strength is in traversing the DOM, and you don't have a node for it to traverse to here.

I suspect the best you're likely to do is something like...

var html = $('#parent-element').html();
html = html.replace("This is a notice to all users", '');
$("#parent-element").html(html);

That is: a brute force replacement of the text. Some simple pattern matching could come into play if you want a little protection against the text changing.

var html = $('#parent-element').html();
html = html.replace(/<input type="checkbox" id="send-notice" name="send-notice" value="1" />.*?</, '');
$("#parent-element").html(html);
VoteyDisciple
There's a chance that the text could be internationalized, so I would need some pattern matching.
Ray
Hmm... for some reason the pattern matching didn't work for me although logically it looks sound.
Ray
+1  A: 

You want to operate on textnodes, and jQuery steers clear of textnodes. Since you can't wrap the text you want to change in a span or something like that, you can, with some effort, identify the textnodes and do some surgery. This is thrown together quickly, but seems to work:

    /* utility function to help us skip whitespace-only nodes */    
    function isWhitespace( thenode ) {
        return !(/[^\t\n\r ]/.test( thenode.data ));
    }   

    /* attach this function to ready() or other trigger */
    function fixtext(){
        $('div#main')
            .contents()
            .filter( function() {
                return !isWhitespace(this) && this.nodeType == 3;
                // nodeType 3 means textNode. Force jQuery to ingest.
            })
            .each( function(){
                $(this).replaceWith( document.createTextNode('Your new text') );
            });
    }

This can certainly be reduced and streamlined, but it seems to work using the information in your question, and should give you a starting point on the approach. It doesn't rely on matching your string exactly -- just that the string will be positioned in some larger container (I have it as div#main here), and it won't have any non-whitespace siblings. Even if your case is more complex, as long as the text is consistently placed you should be able to identify it within the filter() function.

Ken Redler
This works for me! Thanks Ken.
Ray