tags:

views:

851

answers:

5

Hi clever people,

This answer was almost exactly what I needed.

After adding that fn, inline, at the top of my jQ code, I wrote this jQ lower down:

$(":contains(|)").each(function() {
    replaceText('|', 'X');
});

This works, finding all pipe chars across the entire doc and replacing them with X.

However I wanted to replace all pipe chars in a particular div, not across the whole doc. So I changed to:

$("#mySpecificDiv:contains(|)").each(function() {
    replaceText('|', 'X');
});

However, this still replaces all instances across the doc. I am sure I should be using the third option 'node' (see linked-to answer) to limit the scope, but I've tried and failed to find the right syntax.

Sorry that yet again, reading the books and trial and error and past experience has continued to thwart my efforts to master yet another stupidly simple jQ exercise and thanks in advance if you have time to show me what I am doing wrong.

Cheers, -Alan

A: 

Use this:

$( ':contains(|)', $( '#mySpecificDiv' ) ).each(function() {
    replaceText ( '|', 'X', this );
});

$() can accept two arguments. The first is the selector, and the second can be an element to which you limit the search (search based on the selector).

Jan Hančič
Thanks, I used 'this' as part of my solution.
Alan
+1  A: 

try this:

replaceText('|', 'X', document.getElementById("mySpecificDiv"));    

but using replace text function in its current form will replace the first match only. You need to change it to regex to replace all occurances in the div.

Use this to replace all matches in text:

replaceText(/\|/ig, 'X', document.getElementById("mySpecificDiv"));
TheVillageIdiot
Thanks, I used the regex as part of the solution and combined it with 'this' from the alt answer below.
Alan
Yes if there are more than one elements which needs manipulations then $.each is better solution.
TheVillageIdiot
A: 

Yes. You need to specify the node or it will use the body element. Change it to:

$("#mySpecificDiv:contains(|)").each(function() { 
    replaceText('|', 'X', this); 
});

this is a reference to the current node being iterated over in the each function.

tvanfosson
Thanks, I used your use of 'this' for part of the solution.
Alan
A: 

To limit the scope to a specific element.

$('*:contains("|")', '#scopeElement')
czarchaic
Thanks for your comment.
Alan
A: 

In the end, I think the solution below, that works perfectly, is a hybrid of some of the answers (my apologies if your answer is what I have and I've just been so stupid that I didn't realise...).

The following finds a specific div and then recursively replaces each instance of the pipe character, found through use of a regex, with an alternate text string, 'X' in this case.

$("#mySpecificDiv:contains(|)").each(function() { 
    replaceText(/\|/ig, 'X', this); 
});

Brilliant, I would not be here without your answers -- many thanks to all who commented.

Alan