Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change content of div - jQuery

Tags:

jquery

How is it possible to change the content 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> 
like image 573
Oliver 'Oli' Jensen Avatar asked Aug 21 '11 15:08

Oliver 'Oli' Jensen


People also ask

How do I change the content of a div?

Answer: Use the jQuery html() Method You can simply use the jQuery html() method to replace innerHTML of a div or any other element.

What can I use innerHTML instead of jQuery?

For replacing innerHTML of a div with jquery, html() function is used. After loading the web page, on clicking the button content inside the div will be replaced by the content given inside the html() function.

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

You could subscribe for the .click event for the links and change the contents of the 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; }); 

Note however that if you replace the contents of this div the click handler that you have assigned will be destroyed. If you intend to inject some new DOM elements inside the div for which you need to attach event handlers, this attachments should be performed inside the .click handler after inserting the new contents. If the original selector of the event is preserved you may also take a look at the .delegate method to attach the handler.

like image 106
Darin Dimitrov Avatar answered Sep 30 '22 18:09

Darin Dimitrov