Creating HTML Elements With JQuery

jQuery makes it really easy to create HTML elements.

    $("#id").append ( "<div>Some Text</div>" );

Will add the text to the element with an id of 'id'. You can use .html(…) to replace the contents.

A Complete Example (AddSomeText.html):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#placeToAddTo {
	border: 1px solid #ddd;
}
</style>
</head>
<body>

<!-- Click this button to add to the div -->
<button id="Add-To-Div">Add Text To the DIV</button><br>

<!-- Click this button replace the contents of the div -->
<button id="Replace-Div">Replace Text in the DIV</button><br>

<br />
<br />
<!-- Target Div -->
<div id="placeToAddTo"></div>

<script src="js/jquery-1.10.2.js"></script>

<script>

$(function(){
	$("#Add-To-Div").click(function(e){
		$("#placeToAddTo").append ( "<div>Stuff To Add</div>" );
	});
	$("#Replace-Div").click(function(e){
		$("#placeToAddTo").html ( "<div>Replace Stuff</div>" );
	});
});

</script>

</body>
</html>



•       •       •       •       •       •

Summary: # of Words: 63
Author: Philip Schlump
Published On: 2013-05-05

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens