Change div content with jQuery

. Monday, June 9, 2008
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

This is a quick tutorial for understanding the basics of jQuery.

Create a new HTML file with this code:

<html>
<head>
<title>jQuery test page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// javascript here (jQuery)
</script>
</head>
<body>
<--- HTML content here -->
</body>
</html>
Right now, the page will just load the jQuery library.

Lets get some HTML content first
<a id="changeText">Change my text</a>
<br />
<div id="textBox">This text will be changed to something else</div>

jQuery code
Now we will add some javascript so that the content of 'textBox' element changes to something else once you click on 'Change my text' link.
$(document).ready(function() {
$(
"#changeText").click(function() {
$(
"#textBox").html("My text is changed!");
});
});

As soon as your page is loaded in your browser, a function is declared so that whenever you click on the link (with 'changeText' id), the content of the 'textBox' element will be changed to 'My text is changed!'.

Final output:
<html>
<head>
<title>jQuery test page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$(
"#changeText").click(function() {
$(
"#textBox").html("My text is changed!");
});
});
</script>
</head>
<body>
<a id="changeText">Change my text</a>
<br />
<div id="textBox">This text will be changed to something else</div>
</body>
</html>

10 comments:

Anonymous said...

was looking for this for long. thanks :D

Anonymous said...

jQuery rocks! thanks for taking your time and sharing your code :)

metjush said...

dude, cool and simple way to handle this task! thanks a lot, was looking for this...

Furka Tünde said...

Thanks a lot.
I have a question, though. How can I change more div contents respectively? So I have more stuff with different id-s and I'd like to have them changed when I click on a menu item.

Anonymous said...

Can I use this for Wordpress?

Money Off Shop said...

Thanks for sharing that :) Just curious though...could you also open a new browser window (with the destination URL defined in another element) when the click is done on the "changeText" element?

Unknown said...

hi,
if i want to load a html content ?
and if i want to applicate a fade effect ?thx

Anonymous said...

Thanks for your code. Helped me out a lot. I was trying Ajax through JQuery and wanted to load dropdown box on click of a button.

Thanks Again..

Gaurav Kumar
http://www.OSWebStudio.com

7/7 MI5 did it said...

Thanks for sharing such a straight forward example.

This is my jQuery Hello world moment!

neu said...

Simple and to the point! Thanks!