Tag Name Selector in jQuery

jqueryToday, we are going to manipulate HTML elements by selecting them using their tag name.  We are going to perform 3 kinds of selection using tag name.

  • Single Element (Single Tag Name).
  • Multiple Elements (Multiple Tag Names).
  • Element descendant of another Element.

Single Element:  The syntax for selecting single element by tag name is $(‘TagName’).  In the below given example, we are going to select all the div elements and change their background.

<html>
<head>
<title>jQuery Tutorial </title>
 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 
 $(document).ready(function () {
    
    $('div').css("background-color", "red");
 });
 
</script>
</head>
 
<body>

<div><a>First</a></div>
<span><a>Second</a></span>
<div><a>Third</a></div>
 
</body>
</html>

Multiple Elements: It is pretty much similar to previous one, but this time, we are going to separate tag names by comma.  The syntax for selecting multiple elements by tag names is $(‘TagName1, TagName2, TagName3 ’).  In the below given example, we are going to select all the div and span elements and change their background.

<html>
<head>
<title>jQuery Tutorial </title>
 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 
 $(document).ready(function () {
    
    $('div, span').css("background-color", "red");
 });
 
</script>
</head>
 
<body>

<div><a>First</a></div>
<span><a>Second</a></span>
<div><a>Third</a></div>
 
</body>
</html>

Element descendant of another Element:  In jQuery, we can select any element which is descendant of another element.  This can be better understood with an example.  In HTML, DIV element is used as a container. Inside DIV element, we can have more elements.  For these elements, DIV element act as ancestor and all these elements are descendants of DIV element.  Now, to select certain element descendant of DIV element, we use this syntax $(‘DIV TagName’).  In the below given example, we are going to select all anchor elements which are descendant of DIV element.

<html>
<head>
<title>jQuery Tutorial </title>
 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 
 $(document).ready(function () {
    
    $('div a').css("background-color", "red");
 });
 
</script>
</head>
 
<body>

<div><a>First</a></div>
<span><a>Second</a></span>
<div><a>Third</a></div>
 
</body>
</html>