views:

45

answers:

3

Just starting out with jQuery and this problem seems to be impossible to me. Search all the forums, no luck. Maybe you guys can help me?

My html looks kinda like this:

<form>
   <table class="tableClassName"> 
     [content]
   </table>
   <div class="divClassName"> 
     [content]
   </div>
Here is some text
   <div class="divClassName"> 
     [content]
   </div>
</form>

The form has a buch of child elements. I only want to chance the text "here i som text", to something else. Is there some way i can leave all the child elements and only change this particular text?

Here is my noob code, so far:

$(document).ready(function() {
var oldText = "Here is some text";
var newText = "the new text";
var entireElement = $("form:contains(" + oldText + "):not(table, div)").html();
$("form:contains(" + oldText + "):not(table, div)").html(entireElement+newText); 
});

As you can see this replaces nothing. It only puts my new text just before my </form>. What to do?

A: 

Make things simpler to yourself. Use ID's! ;)

New HTML code

<form>
    <table class="tableClassName">[content]</table>
    <div class="divClassName">[content]</div>
    <span id="form_text">Here is some text</span>
</form>

New Javascript Code

$(document).ready(function() {
    var newText = "the new text";
    $('#form_text').html(newText); 
});
Frankie
Yeah. Thats the root of my problem. I cant use ids. Its a CMS-service and i cant edit the html.
sweden
@sweden then go with karim79 answer. And give him credit for it by accepting the answer (click the V next to his answer).
Frankie
A: 

Give this a shot:

$(document).ready(function() { 

  var oldText = "Here is some text"; 
  var newText = "the new text"; 
  var newHtml = $("form:contains(" + oldText + "):not(table, div)").html().replace(oldText,newText);
  $("form:contains(" + oldText + "):not(table, div)").html(newHtml);  

}); 

p.s. This is definitely not the most optimized way to accomplish it.

Fosco
OMG! It worked! You cant believe how much i appreciate this!
sweden
@sweden - If the content of the `<form>` has any jQuery-managed event handlers or other data, just be aware that this will erase all reference to that data. If that's not the case, then this should work just fine.
patrick dw
A: 

If you don't know where your text node is within the container, you might do something like this, i.e., loop over all of them until you get a match:

​$("form").contents().each(function() {
    if(this.nodeType == 3) {
        if($.trim(this.nodeValue) == 'Here is some text') {
            this.nodeValue = 'New text';   
        }
    }
});​​​​​

Demo: http://jsfiddle.net/8yAbu/

karim79
This might actually help me on some other problems im having aswell.Thanx alot!
sweden