0

I'm looking to create a jQuery script that will replace an html variable if and only if it is inside a certain div. I'd like it to do this for each PostID though.

Each variable is unique depending on the post id.

Example:

<div class="[PostID]">
<div class="special">
<div class="container">
(Variable 1 has been replaced by variable 2 here due to the Special class)
[Variable 2]
</div>
</div>
</div>

I created a quick script but the problem I have is that when the first variable 2 is replaced, that is also the variable that is used to replace the following special classes. They aren't using their own variable.

Sorry if this is confusing.

Thank you.

4
  • 2
    Can you show an actual expected-input, and expected-output from using this script? And what script did you try using? Show us what you've worked with, please. And a live demo, at JS Fiddle, or similar, would be extremely helpful! And welcome to Stack Overflow; kudos on, and +1 for, formatting your code correctly in the first instance! =) Commented Jul 7, 2012 at 22:33
  • Do you mean that it's only replacing once? Commented Jul 7, 2012 at 22:39
  • <script type="text/javascript"> $(document).ready(function() { $(".special .container").html($(".container").html().replace('[Variable1]','[Variable2]')); }); </script> Pretty new at jQuery so this is probably awfully coded. Yes @SmokeyPHP it is only replacing once, instead of for each post. I'm not sure how to add in the PostID and make it check for each PostID class. Commented Jul 7, 2012 at 22:39
  • Where does the .container class element appear in your HTML (it's not in your posted HTML). Will the special class be consistent in relation to the changing [PostID] element and the divs of class main? What relation does the [PostID] have on the variables you're replacing? Please, show us your actual (representative) input to the script and the desired output from the script. And please, when showing code, edit your question to include code in the question, not in comments, where it's (more or less) illegible. Commented Jul 7, 2012 at 22:45

2 Answers 2

1

You could iterate over the containers, replacing vars in one at a time with something like this:

$('.special').each(function(){
  $(this).find('.container').html().replace(/V1/g,'V2');
});
Sign up to request clarification or add additional context in comments.

Comments

0

For a global replace you can use the following regular expression method:

string.replace(/\[variable1\]/g,'[variable2]');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.