Changing div content - jQuery

How can I change the contents of this div when one of the LINKS is clicked?

<div align="center" id="content-container"> <a href="#" class="click cgreen">Main Balance</a> <a href="#" class="click cgreen">PayPal</a> <a href="#" class="click cgreen">AlertPay</a> </div> 
+54
jquery
Aug 21 '11 at 15:33
source share
4 answers

You can subscribe to the .click event for links and modify the contents of a div using the .html method:

 $('.click').click(function() { // get the contents of the link that was clicked var linkText = $(this).text(); // replace the contents of the div with the link text $('#content-container').html(linkText); // cancel the default action of the link by returning false return false; }); 

Please note that if you replace the contents of this div, the click handler that you assigned will be destroyed. If you intend to introduce some new DOM elements inside the div for which you need to attach event handlers, these attachments should be done inside the .click handler after inserting the new content. If the original event selector is saved, you can also take a look at the .delegate method to attach the handler.

+96
Aug 21 '11 at 15:35
source share

There are two jQuery features you want to use here.

1) click . This will use the anonymous function as the only parameter and will execute it when the element is clicked.

2) html . This will take the html string as the only parameter and replace the contents of your element with the provided html.

So, in your case, you want to do the following:

 $('#content-container a').click(function(e){ $(this).parent().html('<a href="#">I\'ma new link</a>'); e.preventDefault(); }); 



If you only want to add content to your div, and not replace everything in it, you should use append :

 $('#content-container a').click(function(e){ $(this).parent().append('<a href="#">I\'ma new link</a>'); e.preventDefault(); }); 



If you want the newly added links to also add new content when clicked, you should use event delegation :

 $('#content-container').on('click', 'a', function(e){ $(this).parent().append('<a href="#">I\'ma new link</a>'); e.preventDefault(); }); 
+7
Aug 21 '11 at 15:35
source share
 $('a').click(function(){ $('#content-container').html('My content here :-)'); }); 
+2
Aug 21 '11 at 15:37
source share

Try $('#score_here').html=total;

-2
Oct 22 '13 at 3:56
source share



All Articles