1

I've this code :

<div>
	Hello world.
	<a href="#">test</a>
	<a href="#">login</a>
</div>

I want to replace "hello world." With "Hello everybody !".

I try this :

$('div').text('Hello everybody !');

But it does not work, thanks for your help !

2

5 Answers 5

1

$('div').html($('div').html().replace('Hello world.', 'Hello everybody !'));

Sign up to request clarification or add additional context in comments.

Comments

1

You should do something like this:

<div>
    <div id="greeting">Hello world.</div>
    <a href="#">test</a>
    <a href="#">login</a>
</div>

jQuery:

$("#greeting").html("Hello everybody !");

Comments

0

You can with this code:

$(function() {
  $('div').html($('div').html().replace('Hello world.', 'Hello everybody !'));
});

Comments

0

Try this :

$.fn.myfilter = function(textToReplaceWith)
{
  $(this).contents().filter(function() {

       if(this.nodeType === 3 && $.trim($(this).text()) != "") // nodeType = 3 represents textual content in an element
           $(this).replaceWith(textToReplaceWith);         
    });  
}

$('div').myfilter('Hello everybody !');

Example : https://jsfiddle.net/DinoMyte/6d5ry9br/8/

You may also pass params to replace a specific text dynamically.

$.fn.myfilter = function(textToReplace,textToReplaceWith)
{
  $(this).contents().filter(function() {

       if(this.nodeType === 3 && $.trim($(this).text()) == textToReplace) 
           $(this).replaceWith(textToReplaceWith);         
    });  
}

$('div').myfilter('Hello world.','Hello everybody !');

Example : https://jsfiddle.net/DinoMyte/6d5ry9br/9/

Comments

0
 $('div').html($('div').html().replace('Hello world.', 'Hello everybody !'));

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.