Zhen
Zhen

Reputation: 12431

How to replace content after a container

I have a container as shown below

<div class="container>
</div>

The intention is to add content below the container div. I use the JQuery command '.after'

$('.container').after('Content A')

to get the following result

<div class="container>
</div>
Content A

My question is, how can I replace 'Content A' with 'Content B'? I tried to use the same '.after' command

$('.container').after('Content B')

but I got the following result (which is not what I want)

<div class="container>
</div>
Content B
Content A

So how can I remove 'Content A' and just add 'Content B'?

Upvotes: 0

Views: 153

Answers (1)

jfriend00
jfriend00

Reputation: 707318

Put your new content in a div so you can target it:

$('.container').after('<div class="afterContent">Content A</div>');

Then, to replace it:

$('.afterContent').html('Content B');

It is also possible using plain javascript (not using jQuery) to target just the text node that you inserted the first time and change it's text, but encapsulating it in a div as I've shown makes it much easier.

If you want to see how to modify the text node directly when it's not wrapped in any other type of object, you can see that here: http://jsfiddle.net/jfriend00/BTrrD/. I wouldn't recommend doing it this way (it's the hard way to solve your problem), but I included it for completeness.

Upvotes: 5

Related Questions