In this recipe, you'll learn how to select elements by their tag name using what is known as element selector. The goal of this task is to show you how to select and hide the paragraphs in the page.
To achieve our goal, perform the following the steps:
Create a copy of the
template.html
file and rename it asselecting-by-tag-names.html
.Inside the
<body>
tag, add the following HTML markup:<h1>The Tag name selector</h1> <div> This example shows you how to use a tag name. <p>After you'll click the button below, both the paragraph of this page will be hidden.</p> <p>I'm yet another paragraph</p> </div> <button id="hide-button">Hide elements!</button>
Edit the
<head>
section of the page adding this code:<script> $(document).ready(function() { $('#hide-button').click(function() { $('p').hide(); }); }); </script>
Save the file and open it with your favorite browser.
Although the entire recipe is slightly different from the previous one, it acts differently. As usual, before typing some JavaScript, we set up a short content for our page.
Once the markup is in place, we wrote the listener for the document.ready
event and the click event on the button. Inside the latter, we used the jQuery constructor and passed it a tag name. I chose to hide the two paragraphs, but you can replace it with the tag you prefer. Unlike the other selectors we've seen so far, to collect elements by their tag name, we don't need to add any additional character (as we do in CSS). Thus, to hide the paragraphs, we just pass p
to the constructor and then call the hide()
function.
Tag names can be combined with other selectors. Let's learn how.
The Element selector can be used in conjunction with class and ID selectors to restrict the retrieved collection by just prepending them. For example, we can ask jQuery to hide all of the paragraphs having class red
. To do that, we can write the following code:
$('p.red').hide();
Another example is to use a tag name with an ID. For example we can select the paragraph having as its ID description
, as follows:
$('p#description').hide();
In such cases, jQuery performs a supplementary test before identifying the element as a match. Therefore, it'll retrieve the first (if any) paragraph having ID description. Recalling what I pointed out in the Selecting by ID (Must know) recipe, you should never need to use the tag name with the ID selector since you should have just one element with a given ID.