Creating, getting, and setting content using jQuery

This page discusses - Creating, getting, and setting content using jQuery

Creating, getting, and setting content using jQuery

Creating, getting, and setting content using jQuery

     

Creating, getting, and setting content using jQuery

Using jQuery , you can add(create) html content. For example, if you want to add some html to each 'div' element, you can do it as :

setHtml1.html

<!DOCTYPE html>
<html>
<head>
<style>

.red { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<span>Hello</span>
<div></div>
<div></div>
<div></div>
<script>$("div").html("<span class='red'>Hello <b>Again</b></span>");</script>

</body>
</html>

 

OUTPUT

You can get the html by using jQuery and also can modify it .For example, you can get the paragraph which is clicked and can convert it from html to text :

setHtml2.html

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin:8px; font-size:20px; color:blue; 
      cursor:pointer; }
  b { text-decoration:underline; }
  button { cursor:pointer; }
  </style>
  <script src="/scripts/jquery-1.4.js"></script>
</head>
<body>
	<p>

    <b>Click</b> to change the <span id="tag">html</span>
  </p>
  <p>

    to a <span id="text">text</span> node.
  </p>
  <p>
    This <button name="nada">button</button> does nothing.
  </p>
<script>
    $("p").click(function () {
      var htmlStr = $(this).html();
      $(this).text(htmlStr);
    });
</script>
</body>
</html>

OUTPUT :

The page looks like :

When you click on any paragraph, for example here we click on 'click', it will show you :

You can also set the html content to matched element. For example, you can set the html content to each filtered elememts :

Consider the following code :

<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>

You can set the html content inside 'demo-box' div class using following code :

$('div.demo-container'>
.html('<p>All new content. <em>You bet!</em></p>');

The above line will change the content and produce output something like this :

<div class="demo-container">
<p>All new content. <em>You bet!</em></p>
</div>

Download Source Code

Learn from experts! Attend jQuery Training classes.