jQuery add(selector), add(element) and add(html) example

jQuery add() API can be used to add elements, selectors or html to the matched elements.

The add() method is very useful if you want to apply any jQuery function or add CSS to DOM elements in HTML.

Below example shows how we can use add() to apply CSS styles to ‘table’, ‘p’ and ‘li’ DOM elements in a single line, otherwise we had to apply styles on each element one by one. It also shows how can we add HTML to any DOM element.

<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<style type="text/css">
.styled{
	border:1px black solid;
	background-color: read;
	border-collapse: collapse;
}
</style>
<script type="text/javascript">

	function styleToggle(button) {
		if (button.value == 'Add Style') {
			//using add() we can apply css to all the elements at once
			$('table').add('p').addClass('styled').add('li').css('background-color', 'red');
			button.value = 'Remove Style';
		} else {
			//using removeAttr() to remove the styling
			$('table').add('p').add('li').removeClass('styled').removeAttr('style');
			button.value = 'Add Style';
		}
		$().add("<br /><strong>appending html</strong>").appendTo("p:last");
	}
</script>
<title>jQuery add() Example</title>
</head>
<body>
	<strong>Employee Table</strong>
	<br /><br />
	<table>
		<tbody>
			<tr>
				<th>ID</th>
				<th>NAME</th>
				<th>ROLE</th>
			</tr>
			<tr>
				<td>1</td>
				<td>Pankaj</td>
				<td>Developer</td>
			</tr>
			<tr>
				<td>2</td>
				<td>Mike</td>
				<td>Manager</td>
			</tr>
			<tr>
				<td>3</td>
				<td>David</td>
				<td>CEO</td>
			</tr>
			<tr>
				<td>4</td>
				<td>Lisa</td>
				<td>Support</td>
			</tr>
		</tbody>
	</table>

	<ul>
		<li>list item 1</li>
		<li>list item 2</li>
		<li>list item 3</li>
	</ul>
	<p>A Paragraph</p>
	
	<p>Last Paragraph</p>
	<br />
	<input type="button" value="Add Style" onclick="styleToggle(this)"></input>


</body>

</html>

Try it Yourself

Here are the screenshots of HTML page when we click on the button multiple times.

After clicking on “Add Style” button for first time.

After clicking on “Remove Style” button for first time.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Free Java/Java EE PDF eBooks Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now