jQuery: Multiple way to add a class to all the child elements of an element

By | June 9, 2021

Here in this blog post, I’m going to share with you multiple tricks to add a class to all the child elements of an element.

Suppose, you have created a menu section on your web page and for some reasons, you need to add a class to all the <a> tags within <ul>, that will remove the text decoration of <a> tags.

<ul id="myMenu">
   <li><a href="javascript:void(0);" class="linkClass">JavaScript</a></li>
   <li><a href="javascript:void(0);" class="linkClass">jQuery</a></li>
   <li><a href="javascript:void(0);" class="linkClass">NodeJs</a></li>
   <li><a href="javascript:void(0);" class="linkClass">ReactJs</a></li>
</ul>

Method 1: Using jQuery children() method

jQuery children() method return elements that are direct children of selected element.

$(function() {
  $('#myMenu>li').children('a').addClass('remove_decoration');
});

Method 2: Using jQuery find() method

jQuery find() method return all the child element of a selected element and the child can be grandchild, great-grandchild and so on.

$(function() {
  $('#myMenu>li').find('a').addClass('remove_decoration');
});

Method 3: Using :selector

$(function() {
   $('#myMenu .linkClass').addClass('remove_decoration');
});

Here is the complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery: Multiple way to add a class to all the child elements of an element</title>
  <style>
	#myDiv{width: 300px;border: 15px solid green;padding: 50px;margin: 20px;}
	.remove_decoration{text-decoration:none;}
  </style>
</head>
<body>
	<div id="myDiv" class="abc container inner_div">
	<h4>Welcome to Lipku Tutorials</h4>
	<ul id="myMenu">
		<li><a href="javascript:void(0);" class="linkClass">JavaScript</a></li>
		<li><a href="javascript:void(0);" class="linkClass">jQuery</a></li>
		<li><a href="javascript:void(0);" class="linkClass">NodeJs</a></li>
		<li><a href="javascript:void(0);" class="linkClass">ReactJs</a></li>
	</ul>
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
	$(function() {
	   //$('#myMenu>li').children('a').addClass('remove_decoration'); // using children method
	   //$('#myMenu>li').find('a').addClass('remove_decoration'); // using find method
	   $('#myMenu .linkClass').addClass('remove_decoration'); // using selector
	});
	
  </script>
</body>
</html>

The output: