HTML fonts play an important role in making a website more user-friendly and increasing content readability. Font face and color depend entirely on the computer and browser that are being used to view your page, but you can use the HTML <font> tag to add style, size, and color to the text on your website. You can also use a <basefont> tag to set all of your text to the same size, face, and color.
HTML <font> Tag
The HTML <font> tag specifies the size, color, and face (family) of the text to be displayed on the webpage.
The <font> tag has three attributes called size, color, and face to customize your fonts. To change any of the font attributes at any time within your webpage, simply use the <font> tag with the attribute names and values. The text that follows will remain changed until you close with the </font> tag. You can change one or all of the font attributes within one <font> tag.
The font and basefont tags are deprecated, and they are supposed to be removed in a future version of HTML. So they should not be used; rather, it’s suggested to use CSS styles to manipulate your fonts. But still, for learning purposes, this chapter will explain font and basefont tags in detail.
Set Font Size
To set the font size of a web page, we use the size attribute. This attribute allows us to set the font size between 1 and 7, where 1 is the smallest font size whereas 7 is the largest. The default size of a font is 3.
Example
The following example shows how to use the “size” attribute of the <font> tag to set the font size:
In HTML, relative font size means specifying how many sizes larger or smaller than the preset font size should be. We can specify it like <font size = “+n”> or <font size = “−n”>
Example
The code below demonstrates how to set the relative font size of texts in a web page:
You can set the font face (family) using the face attribute, but be aware that if the user viewing the page doesn’t have the font installed, they will not be able to see it. Instead, the user will see the default font face applicable to the user’s computer.
Example
In this example, we are setting multiple font faces to the text by using the “face” attribute:
Open Compiler
<!DOCTYPE html><html><head><title>Font Face</title></head><body><font face = "Times New Roman" size = "5">Times New Roman</font><br /><font face = "Verdana" size = "5">Verdana</font><br /><font face = "Comic sans MS" size =" 5">Comic Sans MS</font><br /><font face = "WildWest" size = "5">WildWest</font><br /><font face = "Bedrock" size = "5">Bedrock</font><br /></body></html>
Specify Alternate Font Faces
A visitor will only be able to see your font if they have that font installed on their computer. So, we can specify two or more font face alternatives by listing the font face names, separated by a comma.
<font face = "arial, helvetica"><font face = "Lucida Calligraphy, Comic Sans MS, Lucida Console">
When your page is loaded, their browser will display the first font face available. If none of the given fonts are installed, then it will display the default font, Times New Roman.
Setting Font Color
We can set any font color of our choice to the texts using the color attribute. To specify the color, we can use either the color name or hexadecimal code of that color.
Note − You can check a complete list of HTML Color Name with Codes.
Example
The following example illustrates how to set color to the texts on a web page:
Open Compiler
<!DOCTYPE html><html><head><title>Setting Font Color</title></head><body><font color = "#FF00FF">This text is in pink</font><br /><font color = "red">This text is red</font></body></html>
The <basefont> Element
The <basefont> element is used to set a default font size, color, and typeface for any parts of the document that are not otherwise contained within a <font> tag. You can use the <font> elements to override the <basefont> settings.
Like the <font> tag, the <basefont> tag also takes color, size, and face attributes, and it will support relative font setting by giving size a value of +1 for a size larger or −2 for two sizes smaller.
Example
In the below HTML code, we are illustrating the use of the “basefont” tag:
Open Compiler
<!DOCTYPE html><html><head><title>Setting Basefont Color</title></head><body><basefont face = "arial, verdana, sans-serif" size = "2" color = "#ff0000"><p>This is the page's default font.</p><h2>Example of the <basefont> Element</h2><p><font size = "+2" color = "darkgray">
This is darkgray text with two sizes larger
</font></p><p><font face = "courier" size = "-1" color = "#000000">
It is a courier font, a size smaller and black in color.
</font></p></body></html></pre>
The above HTML code will produce four line of text with different font face, color and sizes.
Using Web Safe Fonts in HTML
CSS3 has adapted font combinations technology. If the browser doesn't support the first font, then it tries the next font. Here is the list of CSS Web Safe Fonts.
HTML paragraphs are block-level elements that are used to structure and format text content on a webpage. A paragraph is basically a collection of words and punctuation together. It allows us to organize and present textual information in a coherent and readable manner. The HTML <p> tag is used to create a paragraph element.
Example
This is the first paragraph: Hello World!.
This is the second paragraph: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut purus maximus, efficitur nibh non, gravida odio. Suspendisse justo tortor, consequat sed mauris sit amet, varius fringilla arcu. Duis et elit quis metus molestie lacinia.
Reason to Use Paragraphs
Paragraphs typically create space above and below the text, separating it from surrounding content. They can be styled using CSS to control aspects such as font size, color, alignment, and spacing. In web development, paragraphs play a crucial role in conveying information effectively, enabling clear communication, and enhancing the overall user experience on a website.
Creating a Paragraph
To create a paragraph in HTML, use the <p> tag. Place text inside <p> and </p> that you want to display as a paragraph on a webpage.
Syntax
Below is the syntax to create a paragraph in HTML:
<p>Text to display as a paragraph on the webpage</p>
Example of HTML Paragraph
In the following example, we are creating two paragraphs:
To create two paragraphs:
Open Compiler
<!DOCTYPE html><html><head></head><body><p>Lorem ipsum odor amet, consectetuer adipiscing elit. Proin eros habitant accumsan vulputate curae eu fusce vehicula.</p><p>Laoreet sociosqu taciti iaculis cras leo nec litora. Nisi vehicula massa fusce justo libero duis. Per condimentum vivamus nec elementum nullam sociosqu vel scelerisque.</p></body></html>
Line Breaks With Paragraphs
The <br> tags are used to insert line breaks within a paragraph to control the text layout.
Example
The following example demonstrates how you can use line breaks with the HTML paragraph:
Open Compiler
<!DOCTYPE html><html><head><title>Line Breaks With Paragraphs</title></head><body><p>This is a paragraph with a <br> line break. </p></body></html>
Headings With Paragraphs
Headings, such as <h1>, provide a hierarchical structure and can be used alongside paragraphs.
Example
This example shows a heading with the paragraph:
Open Compiler
<!DOCTYPE html><html><head><title>Headings With Paragraphs</title></head><body><h1>Main Heading</h1><p> This is a paragraph beneath the main heading. </p></body></html>
Lists With Paragraphs
Lists can be incorporated within paragraphs for content organization.
<!DOCTYPE html><html><head><title>Lists With Paragraphs</title></head><body><p>This is a paragraph following an unordered list.</p><ul><li>Item 1</li><li>Item 2</li></ul></body></html>
Emphasis Within Paragraphs
Tags like <em> and <strong> allow you to emphasize text within paragraphs.
Example
This example demonstrates the use of em and strong tags inside a paragraph, like how you can use formatting tags with an HTML paragraph:
Open Compiler
<!DOCTYPE html><html><head><title>Emphasis Within Paragraphs</title></head><body><p> This is a <em> paragraph </em> with <strong> emphasized </strong> text. </p></body></html>
Links within Paragraphs
You can insert links within paragraphs using the <a> tag.
Example
This example demonstrates how you can place the links inside a paragraph:
Open Compiler
<html><head><title>Links within Paragraphs</title></head><body><p>Visit our website <a href="https://www.tutorialspoint.com">here </a>. </p></body></html>
Inline Styles Within Paragraphs
You can use the <span> tag with inline styles to apply specific formatting.
Example
This example demonstrates how you can apply inline CSS styles to some of the parts of the text inside a paragraph:
Open Compiler
<html><head><title>Inline Styles Within Paragraphs</title></head><body><p>This is a <span style="color: blue;">blue</span> text within a paragraph. </p></body></html>
Images Within Paragraphs
You can embed images within paragraphs using the <img> tag.
Example
In this example, we are displaying an image inside a paragraph:
Open Compiler
<html><head><title>Images Within Paragraphs</title></head><body><p> Here's an image: <img src="\html\images\test.png" alt="Example Image"></p></body></html>
Superscript and Subscript Within Paragraphs
Use <sup> and <sub> tags to create superscript and subscript text.
Example
This example demonstrates how you can display superscripted and subscripted text inside a paragraph:
Open Compiler
<html><head><title>Superscript and Subscript Within Paragraphs</title></head><body><p> H<sub>2</sub>O is the chemical formula for water. 2<sup>3</sup> equals 8.</p></body></html>
Abbreviations Within Paragraphs
The <abbr> tag helps define abbreviations or acronyms.
Example
This example shows an abbreviation within a paragraph; it is useful when you want to display an abbreviation or acronym of a specific word:
Open Compiler
<html><head><title>Abbreviations within Paragraphs</title></head><body><p><abbr title="Hypertext Markup Language">HTML</abbr> is used for web development.</p></body></html>
Citations Within Paragraphs
The <cite> tag specifies citations and references within paragraphs.
Example
This example demonstrates the use of the <cite> tag inside a paragraph:
Open Compiler
<html><head><title>Citations Within Paragraphs</title></head><body><p> The book <cite>War and Peace </cite> is a classic novel. </p></body></html>
Styling Paragraph with CSS
The following are the different ways to style HTML paragraphs:
1. Applying CSS Directly to Paragraphs
You can apply CSS styles directly to the paragraphs by writting inline CSS using the ‘style’ attribute with the <p> tag.
Open Compiler
<!DOCTYPE html><html><head></head><body><p style="font-size: 24px; color: #f40;">This is the first paragraph.</p><p>This is the second paragraph.</p><p style="font-size: 24px; background-color: #f40; color: #fff;">This is the third paragraph.</p></body></html>
2. Applying CSS on ‘p’ Element
You can apply CSS styles to all paragraphs within the HTML document by writing CSS rules for the <p> tag.
Open Compiler
<!DOCTYPE html><html><head><style>
p {
font-size: 22px;
color: #f40;
}
</style></head><body><p>This is the first paragraph.</p><p>This is the second paragraph.</p><p>This is the third paragraph.</p></body></html></pre>
3. Using CSS Class with Different Paragraphs
You can apply CSS styles to specific paragraphs by creating a CSS class and using it with the different paragraphs. For this, use the 'class' attribute with the <p> tag.
Open Compiler
<!DOCTYPE html><html><head><style>
.special {
font-size: 24px;
color: #f40;
}
</style></head><body><p class="special">This is the first paragraph.</p><p>This is the second paragraph.</p><p class="special">This is the third paragraph.</p></body></html></pre>
CSS provides extensive control over paragraph styles, allowing you to create visually appealing and well-formatted text on your web page.
HTML headings define the hierarchy (levels) and structure of content on a webpage. They create a visual hierarchy, with the highest-level heading, which is h1, indicating the most important content or the main heading, and lower-level headings like h2, h3, h4, etc. for subtopics.
Reason to use Headings
Headings are crucial for structuring content and providing a clear visual indication of the beginning of new sections or topics. Properly structured headings enhance readability and user experience on websites, ensuring that information is organized and easy to navigate.
Heading Impact on SEO: The well-organized headings help search engines to understand the content structure and indexing.
Highlighting Important Topics: The use of heading tags properly keeps the content readable.
HTML Heading Tags
The headings are defined with headings tags (<h1> to <h6>). It is important to use heading tags to show the content structure on a webpage. HTML has a different level of heading tags. The hierarchy determines the importance of content and aids in creating a clear information flow for both users and search engines.
Example
The following example shows the different levels of the HTML heading −
Open Compiler
<!DOCTYPE html><html><body><h1>This is Heading 1 (H1 Tag)</h1><h2>This is Heading 2 (H2 Tag)</h2><h3>This is Heading 3 (H3 Tag)</h3><h4>This is Heading 4 (H4 Tag)</h4><h5>This is Heading 5 (H5 Tag)</h5><h6>This is Heading 6 (H6 Tag)</h6></body></html>
Hierarchical Structure of Heading Tags
Below is the list according to the hierarchy of the heading tags (most to least significant) −
The <h1> Tag − The top-level heading denotes the main topic or title of the entire page.
The <h2> Tag − Subheadings under <h1> represent major sections related to the main topic. They provide a more specific context to the content.
The <h3> to <h6> Tags − These tags are used for further subsections or nested content within <h2> headings. They offer a deeper level of hierarchy for organizing content within specific sections.
Examples of HTML Headings
In these examples, you will see the usage of all the heading tags to create different types of headings and styling them using the CSS −
Headings Using <h1> to <h6> Tags
In this example, we will use the heading tags (h1 to h6); each of them has a different size and weight for the content −
Open Compiler
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Example of HTML Headings</title></head><body><h1>Heading 1: Main Heading of Page</h1><h2>Heading 2: Section</h2><h3>Heading 3: Subsection</h3><h4>Heading 4: Sub-subsection</h4><h5>Heading 5: Lower-level heading</h5><h6>Heading 6: Lowest-level heading</h6></body></html>
Styling Headings With CSS
In the following example, we will apply the style such as font family, font color, font size, etc. to the headings −
Open Compiler
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Example of HTML Headings</title><style>
Here, we have applied "Verdana" font style to all heading tags, defined the "Red" color to H1 heading with the font size 32px, and defined the "Green" color to H2 heading with the font size 30px.
Using HTML Tags Within Heading Tags
HTML headings (h1 to h6) serve as the main titles and subheadings for content organization. Within these heading tags, you can use various other HTML tags to enhance and structure your content effectively. Here are some examples −
The <span> Tag
You can use the <span> tag to apply inline styles or classes to specific portions of the text within a heading. This allows for custom styling of text within the heading.
Open Compiler
<!DOCTYPE html><html><head><title>Using <span> Tag</title></head><body><h2>This is a <span style="color: blue;">blue</span> word.</h2></body></html>
The <a>Tag for Links
To create a link within a heading, use the <a> tag. This is useful for headings that lead to other pages or sections of your website.
Open Compiler
<!DOCTYPE html><html><head><title>Using <a> Tag for Links</title></head><body><h1><a href="https://www.tutorialspoint.com">Visit our website</a></h1></body></html>
The <em> and <strong> Tags
These tags are used for emphasizing text within headings. The <em> tag italicizes the text, while <strong> makes it bold.
Open Compiler
<!DOCTYPE html><html><head><title>Using <em> and <strong> Tags</title></head><body><h3>This is <em>emphasized</em> and <strong>important</strong> text.</h3></body></html>
The <sup> and <sub> Tags
In heading, to include superscript or subscript text within a heading, use <sup> and <sub>.
Open Compiler
<!DOCTYPE html><html><head><title>Using <sup> and <sub> Tags</title></head><body><h4>The 10<sup>th</sup> floor is at the top.</h4><h5>The chemical formula for water is H<sub>2</sub>O.</h5></body></html>
The <abbr> Tag for Abbreviations
When you need to include an abbreviation or acronym in a heading, use the <abbr> tag. It often provides a tooltip with the full meaning.
Open Compiler
<!DOCTYPE html><html><head><title>Using <abbr> Tag for Abbreviations</title></head><body><h2>HTML stands for <abbr title="Hypertext Markup Language">HTML</abbr>.</h2></body></html>
The <br> Tag for Line Breaks
Sometimes, you might want to create line breaks within a heading for better formatting. The <br> tag serves this purpose.
Open Compiler
<!DOCTYPE html><html><head><title>Using <br> Tag for Line Breaks</title></head><body><h3>This is the first line.<br>This is the second line.</h3></body></html>
The <mark> Tag
Use the <mark> tag to highlight specific text within a heading. It's often used to indicate search results or selected portions of text.
Open Compiler
<!DOCTYPE html><html><head><title>Using <mark> Tag</title></head><body><h1>Search for "<mark>important</mark>" information here.</h1></body></html>
Mistakes to be Avoided
Make sure we avoid the following mistakes while using the heading tag −
HTML attributes are special words that provide additional information to an HTML element. Attributes are placed inside the element’s opening tag, and they are used to configure or adjust the element’s behavior. All attributes are made up of two parts: a name and a value −
Name: The attribute name is the keyword, also known as the attribute identifier, which defines a specific characteristic for the element in which it is using. For example, the paragraph <p> element (in the below-given example) has an attribute “align“, which defines the alignment of the paragraph on the page.
Value: The attribute value is the data or information that defines the value to be set for that attribute. The value is assigned within the double quotes. For example, “left“, “center“, or “right” can be assigned to the “align” attribute with the paragraph tag (as shown in the below example).
Below is the syntax of an element HTML having attribute −
<tag_name attribute="Value">...</tag_name>
Rules and Characteristics
The following are the rules and characteristics of HTML attributes; you should follow while using attributes with HTML elements:
Attributes are optional; you can use them to provide additional information about an HTML element.
Attributes have name and value pairs, but some of the attributes do not require any value; those are known as Boolean attributes.
An HTML element can have multiple attributes, and they should be separated by spaces.
Attributes should always be written with the opening tag.
All HTML elements can have attributes except a few like <head>, <title>, <script>, etc.
W3C recommends using attributes in lowercase and keeping the value in quotes.
Example of HTML Attributes
This example demonstrates the use of attributes with HTML elements −
Open Compiler
<!DOCTYPE html><html><head><title>Example of HTML Attributes</title></head><body><a href="https://www.tutorialspoint.com">Visit our homepage</a></body></html>
In this example, href is the attribute name and “https://www.tutorialspoint.com” is the attribute value.
Core Attributes Every Element Can Use
The four core attributes that can be used on the majority of HTML elements (although not all) are −
The id Attribute
The id attribute of an HTML tag can be used to uniquely identify any element within an HTML page. There are two primary reasons that you might want to use an id attribute on an element −
If an element carries an id attribute as a unique identifier, it is possible to identify just that element and its content.
If you have two elements of the same name within a Web page (or style sheet), you can use the id attribute to distinguish between elements that have the same name.
We are using the id attribute to distinguish between two paragraph elements −
Example
Open Compiler
<!DOCTYPE html><html><head><title>ID Attribute Example</title></head><body><p id="html">This para explains what is HTML</p><p id="css">This para explains what is Cascading Style Sheet</p></body></html>
The title Attribute
The title attribute gives a suggested title for the element. The syntax for the title attribute is similar as explained for id attribute −
The behavior of this attribute will depend upon the element that carries it, although it is often displayed as a tooltip when the cursor comes over the element or while the element is loading.
Example
Open Compiler
<!DOCTYPE html><html><head><title>The title Attribute Example</title></head><body><h3 title="Hello HTML!">Titled Heading Tag Example</h3></body></html>
On executing the above example, it will display the heading “Titled Heading Tag Example”. If you bring your cursor over it, you will see that whatever title you used in your code is coming out as a tooltip of the cursor.
The class Attribute
The class attribute specifies one or more CSS classes for an HTML element. Multiple classes can be used on a single element with this attribute. The value of this attribute is a space-separated list of class names if you are specifying multiple classes.
Example
class="className1 className2 className3"
The style Attribute
The style attribute allows you to write inline CSS rules for an element.
Example
Open Compiler
<!DOCTYPE html><html><head><title>The style Attribute</title></head><body><p style="font-family:arial; color:#FF0000;">Welcome to Tutorialspoint...</p></body></html>
On executing the above example, it will display the text “Welcome to Tutorialspoint…” in the “Arial” font and with a red color.
Internationalization (i18n) Attributes
There are three internationalization attributes, which are available for most (although not all) XHTML elements.
The dir Attribute
The dir attribute allows you to indicate to the browser about the direction in which the text should flow. The dir attribute can take one of two values, as you can see in the table that follows −
S.No
Value & Meaning
1
ltrLeft to right (the default value)
2
rtlRight to left (for languages such as Hebrew or Arabic that are read right to left)
Example
Open Compiler
<!DOCTYPE html><html dir="rtl"><head><title>Display Directions</title></head><body>
This is how IE5 renders right-to-left directed text.</body></html>
If you click on Edit & Run, you can observe the text aligned to right.
When dir attribute is used within the <html> tag, it determines how text will be presented within the entire document. When used within another tag, it controls the text’s direction for just the content of that tag.
The lang Attribute
The lang attribute allows you to indicate the main language used in a document, but this attribute was kept in HTML only for backwards compatibility with earlier versions of HTML. This attribute has been replaced by the xml:lang attribute in new XHTML documents.
The values of the lang attribute are ISO-639 standard two-character language codes. Check HTML Language Codes: ISO 639 for a complete list of language codes.
Example
Open Compiler
<!DOCTYPE html><html lang="en"><head><title>English Language Page</title></head><body>
This page is using English Language
</body></html>
Boolean Attributes
Boolean attributes represent true and false values and do not require any value with the attribute name. To set the true value, you need to write the attribute’s name, and to set it false, the attribute should be omitted altogether.
Here are some Boolean attributes –
disabled
readonly
required
inert
autocomplete
Example
Here is an example of an HTML Boolean attribute (required) −
Open Compiler
<!DOCTYPE html><html><body><h1>Example of "required" attribute</h1><form><label for="user_name">Input User Name:</label><input type="text" id="user_name" name="user_name" required><input type="submit"></form></body></html>
The xml:lang Attribute
The xml:lang attribute is the XHTML replacement for the lang attribute. The value of the xml:lang attribute should be an ISO-639 country code, as mentioned in the previous section.
Generic Attributes
Here’s a table of some other attributes that are readily usable with many of the HTML tags.
Names an element for use with Cascading Style Sheets.
class
User Defined
Classifies an element for use with Cascading Style Sheets.
width
Numeric Value
Specifies the width of tables, images, or table cells.
height
Numeric Value
Specifies the height of tables, images, or table cells.
title
User Defined
“Pop-up” title of the elements.
href
User Defined
Specifies the destination URL for a link or reference.
src
User Defined
Specifies the source file for media elements like <img>, <audio>, or <iframe>.
We will see related examples as we proceed to study other HTML tags. For a complete list of HTML tags and related attributes, visit: HTML Tags Reference and HTML Attributes Reference.
Best Practices for Using HTML Attributes
There are certain practices you should follow to use attributes on any element, please check the below-mentioned ways to do so:
1. Write Values in Quotes
You should always write the attribute values in single or double quotes.
<!-- Good Practice --><a href="https://www.tutorialspoint.com/html/html_overview.htm">
HTML Introduction
<a><!-- Bad Practice --><a href=https://www.tutorialspoint.com/html/html_overview.htm>
HTML Introduction
<a>
2. Use Lowercase
HTML is case-insensitive, but the good practice is to write the HTML attribute in lowercase.
<input type="text">
3. Use of Single and Double Quotes Together
When you need to provide any string in quotes as the value of an attribute, you can use the combination of single and double quotes.
<!-- Can use single and double Quotes --><p title="We are known for 'Simple Easy Learning'">
Tutorialspoint
</p><p title='We are known for "Simple Easy Learning"'>
An HTML element is a fundamental component of an HTML document that can contain data to display on the webpage, such as text, image, link, or sometimes nothing. An HTML element includes an opening tag, content, and a closing tag, where the opening tag may also include attributes.
An HTML element includes:
Opening Tag: An opening tag specifies the beginning of the element and may include multiple attributes.
Content: The content part includes the information to be displayed or processed within an element.
Closing Tag: A closing tag marks the end of the element (A closing tag may be optional for some elements).
An HTML document consists of a tree of HTML elements, and they define the content and layout of a webpage, like how and what content should display in the different sections of a webpage.
Example of HTML Elements
Some of the examples of HTML elements are as follows:
<p>This is paragraph content.</p><h1>This is heading content.</h1><div>This is division content.</div>
The following table displays the different parts (opening tag, content, and closing tag) of the HTML elements used in the above example:
Opening Tag
Content
Closing Tag
<p>
This is paragraph content.
</p>
<h1>
This is heading content.
</h1>
<div>
This is division content.
</div>
So here <p>…</p> is an HTML element, <h1>…</h1> is another HTML element.
HTML Element Structure
The following image demonstrates the structure of an element, like how an HTML element is written with the opening and closing tags:
Elements vs. Tags: What’s the Real Difference?
This is the most common point of confusion for beginners. Here’s a simple way to think about it:
An HTML Tag is just the opening <p> or closing </p> part. They are the instructions.
An HTML Element is the entire thing: the opening tag, the content inside, and the closing tag.
Think of it like a sandwich. The two slices of bread are the tags, and the complete sandwich with everything inside is the element.
Understanding Nested Elements
HTML allows nesting of elements. The nested elements are created by placing one or more HTML elements inside an HTML element. Where the container element can be considered as a parent element and others are as child elements. The child elements are nested inside the parent element. We can have multiple levels of nesting; however, it requires some guidelines to follow −
Every opening tag must have a corresponding closing tag.
The closing tag of the parent element must come after the closing tag of the child element.
The nested elements must be valid HTML elements.
Example
In the following example, we are nesting the italicized element (<i>…</i>) within the h1 element and underline (<u>…</u>) element within the paragraph element.
Open Compiler
<!DOCTYPE html><html><head><title>Nested Elements Example</title></head><body><h1>This is <i>italic</i> heading</h1><p>This is <u>underlined</u> paragraph</p></body></html>
On executing the above example, we can observe the two sentences where we have nested one HTML within another.
Note: In the above example, the <html>, <head>, and <body> tags are also nested elements as they have one or more elements inside them.
Special Case: Empty (Void) Elements
HTML void elements are those elements that don’t require closing tags. These tags don’t have any content model and even don’t allow nesting of elements. The void elements are also known as empty or self-closing elements.
Some of the void elements are such as <img />, <hr />, and <br /> elements. The below table shows a list of void elements −
S.No
Elements & Description
1
<img>Used for inserting images within HTML documents.
<source>It is used for embedding media resources like audio and video.
Note: You might see these tags written with a / at the end, like <br />. This is an older syntax and is not needed in modern HTML5.
Example
The following example demonstrates the example of HTML void elements −
Open Compiler
<!DOCTYPE html><html><body><p>This line contains a line break tag, <br> hence content is visible in two separate lines.</p><p>This line is <hr>separated by a horizontal rule.</p></body></html>
On executing, the above code will produce two paragraphs, one with a line break and the other with a horizontal rule.
Attributes With HTML Elements
The attributes can be placed with an opening tag by using the pairs of attribute name and value. Multiple attributes can be separated with a space.
The following statement demonstrates the use of two attributes src and alt with an HTML element img:
<img src="logo.jpg" alt="TutorialsPoint Logo" />
Mandatory Closing HTML Elements
The HTML elements that are opened must be closed. Only the void elements like <img />, <hr />, <br />, etc. do not require closing tags; other elements such as <p> and <h1> require closing tags after the content part.
If any HTML element does not include a closing tag, it may not cause an error, and some content may still display properly. However, never miss the closing tag, as it may lead to unexpected and inconsistent results.
Example
In this example, we are removing the closing tags from the paragraph tag. Still, it will show the correct result.
Open Compiler
<!DOCTYPE html><html><body><p>This line contains a line break tag, <br /> hence content is visible in two separate lines.
<p>This line is <hr /> separated by a horizontal rule.
</body></html>
The above HTML code will produce two paragraphs, one with a line break and the other with a horizontal rule.
Are HTML Elements Case-sensitive?
No, HTML elements are not case-sensitive, which means we can write HTML elements either in uppercase or lowercase. However, it is not a good practice, as W3C recommends and demands lowercase. Hence, always try to use lowercase for the tag names.
Example
In the following example, we are writing HTML elements (tag names) in uppercase and mixed case (uppercase and lowercase); see the output; there is no error and HTML code runs fine −
Open Compiler
<!DOCTYPE html><HTml><BODY><P>HTML is not case sensitive i.e we can use both upper or, lower case letters in the tags.</p></BOdy></html>
HTML tags are the fundamental elements of HTML used for defining the structure of the document. These are letters or words enclosed by angle brackets (< and >).
Usually, most of the HTML tags contain an opening and a closing tag. Each tag has a different meaning, and the browser reads the tags and displays the contents enclosed by them accordingly.
For example, if we wrap any text in the paragraph (<p></p>) tag, the browser displays it as a separate paragraph. In this tutorial, we will discuss all the basic tags in HTML.
Heading Tags
Heading tags are used to define headings of documents. You can use different sizes for your headings. HTML also has six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. While displaying any heading, the browser adds one line before and one line after that heading.
Example
Following HTML code demonstrates various levels of headings:
Open Compiler
<!DOCTYPE html><html><head><title>Heading Example</title></head><body><h1>This is heading 1</h1><h2>This is heading 2</h2><h3>This is heading 3</h3><h4>This is heading 4</h4><h5>This is heading 5</h5><h6>This is heading 6</h6></body></html>
Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of text should go in between an opening <p> and a closing </p> tag.
Example
The following example demonstrates the use of paragraph (<p>) tag, here we are defining 3 paragraphs −
Open Compiler
<!DOCTYPE html><html><head><title>Paragraph Example</title></head><body><p>Here is a first paragraph of text.</p><p>Here is a second paragraph of text.</p><p>Here is a third paragraph of text.</p></body></html>
Line Break Tag
The <br> tag is used to insert a line break in the text. It forces the content after it to appear on the next line. This tag is used whenever you want the text to break into a new line without starting a new paragraph.
Note: The <br> tag is an empty tag and does not need a closing tag.
Example
The following example demonstrates the use of break (<br>) tag −
Open Compiler
<!DOCTYPE html><html><head><title>Line Break Example</title></head><body><p>Hello<br>You delivered your assignment on time.<br>Thanks<br>Mahnaz</p></body></html>
Center Tag
In HTML, the alignment should be handled using CSS rather than deprecated tags. The <center> tag, previously used to align content to the center of a web page, is deprecated in HTML5. You can use the text-align: center; property of CSS to center text or inline elements.
Example
The following example demonstrates how to center a paragraph using CSS:
text-align: center;}</style></head><body><p>This text is not in the center.</p><p class="center-text">This text is in the center.</p></body></html></pre>
Horizonal Rule Tag
The <hr> tag is used to insert a horizontal line across the page. It is commonly used to separate sections of content visually.
Note: Like <br> tag, the <hr> tag is also an empty tag and does not need a closing tag.
Example
The following example draws a horizontal line between two paragraphs −
Open Compiler
<!DOCTYPE html><html><head><title>Horizontal Line Example</title></head><body><p>This is paragraph one and should be on top.</p><hr><p>This is paragraph two and should be at bottom.</p></body></html>
On executing the above example, you can see a straight line dividing the two paragraphs.
The <hr /> tag is an example of the empty element, where you do not need opening and closing tags, as there is nothing to go in between them.
The <hr /> element has a space between the characters hr and the forward slash. If you omit this space, older browsers will have trouble rendering the horizontal line, while if you miss the forward slash character and just use <hr>, it is not valid in XHTML.
Preserve Formatting Tag
The <pre> tag is used to preserve the formatting. Whenever you want to display content on the webpage exactly in the same format as it was written in the HTML document, you can use the <pre> tag. It preserves the formatting of source code, including line breaks and indentation.
Example
The following example demonstrates the use of the <pre> tag. Here, we are displaying some code that should keep the formatting exactly the same as it is written inside the <pre> tag −
function testFunction( strText ){
alert (strText)
}
Non-breaking Spaces
Non-breaking spaces prevent an automatic line break and are displayed using the entity.
Suppose if you want to use the phrase "12 Angry Men." Here, you would not want a browser to split the "12, Angry" and "Men" across two lines −
An example of this technique appears in the movie "12 Angry Men."
In cases, where you do not want the client browser to break text, you should use a nonbreaking space entity instead of a normal space. For example, when coding the "12 Angry Men" in a paragraph, you should use something similar to the following code −
Example
The following example demonstrates the use of entity −
Open Compiler
<!DOCTYPE html><html><head><title>Nonbreaking Spaces Example</title></head><body><p>An example ofthis technique appears in the movie "12 Angry Men."</p><p>An example ofthis technique appears in the movie "12 Angry Men."</p></body></html>
On executing the above example, it will display the sentence: An example of this technique appears in the movie "12 Angry Men." twice. Since we have added 3 " " characters between 12 and men, the second time, you can observe three spaces.
Listing Tags
The <ul> and <ol> tags create the unordered and ordered listings, and to display list items, the <li> tag is used.
Example
The following example demonstrates the use of listing tags −
HTML editors are used to create, edit, and manage HTML code. In this tutorial, you will learn about the popular HTML editors that can be used to manage your HTML documents. Here, we are explaning the steps to create and run HTML code in the specific editors.
What are HTML Editors?
HTML editors are tools/software to create, edit, manage, and run (in some cases) HTML documents. HTML editors provide many features, such as auto-indenting, syntax highlighting, autocompletion, etc.
You can use any of the HTML editors mentioned below to write and manage your HTML codes. You need to save the file with an extension .htm or .html.
Types of HTML Editors
The following are the different types of HTML editors:
Text Editors: Text editors are the basic HTML editors where you need to write the code manually. These types of editors don’t provide all features required for writing and managing HTML codes. Some of the text editors may include features like syntax highlighting and basic code editing tools. Example: Notepad, Notepad++, etc.
WYSIWYG Editors: WYSIWYG Editors allow you to create web pages visually where you need to write the complete code manually. These types of HTML editors provide designing pages without needing to write code. Examples: Adobe Dreamweaver, BlueGriffon, etc.
Online HTML Editors: The online HTML editors are web-based tools where you can write, manage, and run your HTML codes directly in your browser. These editors often provide live previews of the HTML documents. We provide an online HTML editor that supports syntax highlighting, alignment, code beautification, and many more features. You can use our HTML Editor to write, edit, and manage your HTML code.
Integrated Development Environments (IDEs): The IDEs provide an integrated development environment where you can write, manage, and debug complete or larger projects. Some of the IDEs are JetBrains, WebStrom, Eclipse, etc.
Popular HTML Editors in 2025
There are several HTML editors available to the user (paid and unpaid, both). The following is the list of some popular editors:
Notepad
TextEdit
Notepad++
Sublime
Visual Studio Code
Atom
Brackets
Adobe Dreamweaver CC
CoffeeCup
1. Notepad
Notepad is a basic free text editor which is preinstalled in Windows systems. Notepad can be used as an HTML Editor.
Steps to Create and Run HTML Code in Notepad
The following are the steps to create and run an HTML document in Notepad:
Open notepad application.
Write your HTML code.
Save the file with an extension “.htm” or “.html” and set the encoding to UTF-8.
Now, you can open this HTML document in any web browser.
2. TextEdit
TextEdit is a default text editor and an open-source word processor that comes with MacOS. You can use TextEdit as an HTML editor to create, edit, and manage your HTML code. You can also use it to display HTML documents like you see them in a browser or in code-editing mode.
The only limitation in TextEdit is that it doesn’t display images when you use it to browse webpages.
Steps to Create and Run HTML Code in TextEdit
The following are the steps to create and run an HTML document in TextEdit:
Open TextEdit
Create a new file
Go to the “format” then Make Plain Text
Write your HTML code
Save the with an extension “.htm” or “.html”
3. Notepad++
Notepad++ is a free source code editor. It is written in C++ and supports features like, syntax highlighting, limited auto completion for programming, scripting, etc. Notepad++ is one of the best HTML code editors where you can create and manage HTML documents.
Notepad++ does not come with preinstallation, you need to download it manually from the different devices from its official website: notepad-plus-plus.org
Steps to Create and Run HTML Code in Notepad++
To create an HTML document in Notepad++:
Open Notepad++
Open a new file, write your HTML code, and save the file as “.html”or “.htm”
Click on the file and select the browser in which you want to view the results.
4. Sublime Editor
Subline editor is a cross-platform source code editor. It is used to write Codes, markup, and prose. It is written in C++ and Python.
Sublime editor provides features like quick navigation to files, symbols, or lines. It allows you to simultaneously edit multiple selected area.
Sublime editor can be downloaded from this link: Sublime Text
5. Visual Studio Code
Visual Studio Code (VS Code) is also a source-code editor developed by Microsoft. It supports Windows, Linux, and macOS. VS code is widely used for creating and managing HTML documents due to its amazing features like debugging support, syntax highlighting, code refactoring, intelligent code completion, etc.
Atom is an open-source text and source code editor for MacOS. Atom can also be used in Windows systems after downloading and installing. Atom is also a free editor and can be used as an HTML editor where you can create and manage HTML documents. It provides various features such as syntax highlighting, code completion, find and replace, auto detect indentation, and different themes.
The steps to write and run HTML in the Atom editor are:
Steps to Create and Run HTML Code in Atom
Create/open a file
Write or paste HTML code.
Save file with “.htm” or “.html” extension.
And, press “CTRL + Shift + B” (in Windows) to run and see the preview.
7. Brackets Editor
Brackets is a source code editor that can be used for creating and managing HTML documents. Brackets is created by Adobe, and it is useful for web development. Brackets features include auto saving, code beautification, live preview, and many more.
Steps to Create and Run HTML Code in Brackets
The steps to create an HTML document in brackets editors are:
Download & Install Bracket Editor
Create a new file.
Write HTML code and save the files with the extension “.htm” or “.html“.
8. Adobe Dreamweaver CC
Adobe Dreamweaver CC is a premium IDE application for web development and source code editing, like HTML editors. It offers toolkits for designing and creating websites that combine a visual design interface with a code editor.
It supports many programming languages like Python and HTML, enabling efficient coding for both beginners and advanced users, and also provides Git support. It is a subscription-based model as it ensures access to regular updates and customer support for assistance.
9. CoffeeCup
CoffeeCup is a paid HTML editor software known for its user-friendly interface and powerful features. It offers a range of tools for web development, including code editing, site management, and responsive design support.
With CoffeeCup, users can create and edit HTML, CSS, and JavaScript code efficiently. It provides live previews, code validation, and an integrated FTP client for seamless website management.
How HTML Editors can benefit you?
There are several advantages to using HTML editors to write and manage your HTML codes. Some of the main advantages are as follows:
Error Reduction: HTML editors are useful to identify and correct the syntax errors during writing the HTML codes.
Syntax Highlighting: Most of the HTML editors come with the syntax highlighting features that enable color-coding to distinguish HTML tags, attributes, and content that makes the code clear and readable.
Code Autocompletion: Most of the HTML editors autocomplete the tags or attributes while writing the code. For example, if you start writing a paragraph and type <p>, editors will automatically insert a closing tag </p>. The editors also suggest the syntax of the elements.
Code Validation: Most of the HTML editors have code validating features; you don’t need any other tool to validate your code. This feature helps to validate the errors.
Collaboration Tools: Some of the HTML editors come with version control systems that make it easier for teams to collaborate and track changes.
Chapter Summary
HTML editors are used to write, edit, and manage HTML codes.
There are various types of HTML editors, such as text editors, WYSIWYG editors, online HTML editors, and integrated development environments (IDEs).
The popular and widely used HTML editors are Notepad, TextEdit, Notepad++, Sublime, Visual Studio Code, Atom, Brackets, Adobe Dreamweaver CC, and CoffeeCup.
These HTML editors provide many features, such as error reduction, syntax highlighting, code completion, code validation, collaboration tools, and more.
HyperText Markup Language (HTML) was initially developed by Sir Tim Berners-Lee in late 1991. It was designed as a standard language for creating and formatting documents on the World Wide Web. All the web pages on the internet are made from HTML.
From 1990 to 1995, HTML underwent changes and extensions, initially at CERN and then at the IETF. The World Wide Web Consortium (W3C) became the new home for HTML development.
The Idea of Hypertext Before HTML
We must first examine the idea of hypertext in order to comprehend the origins of HTML. Early 20th-century pioneers like Vannevar Bush proposed the concept of tying information together through hypertext, envisioning a “memex” machine that could organize enormous volumes of information using linked microfilm.
However, Ted Nelson, an American philosopher and sociologist, first used the word “hypertext” in the 1960s. Nelson’s idea of hypertext was to develop a network of connected text and multimedia that permitted non-linear information navigation.
The Timeline of HTML’s Evolution
Here you will see the evolution of HTML over the past couple of decades. The major upgrade was done in HTML5 in 2012.
Year
Progress
1991
Tim Berners-Lee created HyperText Markup Language but it was not officially released.
1993
Tim Berners-Lee created the first version of HTML that was published and available to the public.
1995
HTML 2.0 was released with a few additional features along with the existing features.
1997
There was an attempt to extend HTML with HTML 3.0, but it was replaced by the more practical HTML 3.2.
1998
The W3C (World Wide Web Consortium) decided to shift focus to an XML-based HTML equivalent called XHTML.
1999
HTML 4.01, which became an official standard in December 1999, was the most widely used version in the early 2000s.
2000
XHTML 1.0, completed in 2000, was a combination of HTML4 in XML.
2003
The introduction of XForms reignited interest in evolving HTML itself rather than replacing it with new technologies. This new theory recognized that XML was better suited for new technologies like RSS and Atom, while HTML remained the cornerstone of the web.
2004
A W3C workshop took place to explore reopening HTML’s evolution. Mozilla and Opera jointly presented the principles that later influenced HTML5.
2006
The W3C expressed interest in HTML5 development and formed a working group to collaborate with the WHATWG. The W3C aimed to publish a “finished” HTML5 version, whereas the WHATWG focused on a Living Standard, continuously evolving HTML.
2012
HTML5 can be seen as an extended version of HTML 4.01, which was officially published in 2012.
From HTML 1.2 to HTML 5 to – How HTML’s Features Evolved Over Time
With the introduction of new versions of HTML, support for additional features was added, and the user experience was enhanced. The following table shows the features introduced in later versions of HTML:
Type of Content
HTML 1.2
HTML 4.01
HTML 5
Description
Image
Yes
Yes
Yes
The img tag allows to add images to HTML document
Paragraph
Yes
Yes
Yes
Paragraph element in HTML is used to represent a paragraph of text on a webpage.
Heading
Yes
Yes
Yes
Heading are used in HTML to define variable length headings. (h1 to h6)
Address
Yes
Yes
Yes
Address element in HTML is used to contain contact information of user.
Anchor
Yes
Yes
Yes
Anchor tag is used to define hyperlink in webpage.
List
Yes
Yes
Yes
List is used in HTML to display list of related items.
Table
No
Yes
Yes
Table is used to organize data into rows and columns
Style
No
Yes
Yes
Style is used to add CSS styling to webpage
Script
No
Yes
Yes
Script is used to add JavaScript to HTML.
Audio
No
No
Yes
Enables introduction of audio to webpage
Video
No
No
Yes
Enables introduction of video to webpage.
Canvas
No
No
Yes
Enables introduction of graphics elements to webpage.
HTML stands for HyperText Markup Language. It is used to structure the content on the web by using various elements (commonly known as tags). These HTML elements define the different sections of a web page, such as headings, paragraphs, links to other webpages, listings, images, tables, etc. These elements tell the browser about the content and formatting to display.
HTML is HyperText + Markup Language. Where,
HyperText refers to the way in which Web pages (HTML documents) are linked together. Thus, the link available on a webpage is called “HyperText”.
Markup Language, which means you use HTML to simply “mark up” a text document with tags that tell a Web browser how to structure it to display.
What is an HTML Element?
An HTML element is a basic building block to create a webpage, and It is created by a start tag, content, and end tag. In an HTML element, the content is placed between a start and end tag.
The basic syntax of an HTML element is −
<tag_name>content</tag_name>
Consider the following example demonstrates an HTML element −
<h1>It is top-level heading</h1>
Here,
<h1> is the start tag.
“It is top-level heading” is the content, which is placed inside the start and end tags.
</h1> is the closing tag.
HTML Page Structure
HTML page structure (or, HTML basic structure) consists of the essential elements that are required to create an HTML document that can be displayed on the browser.
The following image shows the page structure of an HTML document −
HTML page structure contains <!DOCTYPE html>, <html>, <head>, <title>, <body>, and other tags that will be shown on the homepage.
Where,
<!DOCTYPE html> − It defines the document type as HTML.
<html> − It is a root element for an HTML document. All elements are placed inside this element.
<head> − The head tag may contain scripts and styles that are useful page functionalities. Meta tags are also placed inside this tag.
<title> − It defines the webpage’s title.
<body> − It defines the body of the webpage, all elements that are used to display content on the browser placed inside the body tag.
<h1> and <p> − The h1 tag defines page heading, and p tag defines paragraph.
Web Browser Role
The role of a web browser is to read HTML documents from the given path (either from the server or from a local device) and display it on the webpages. All web browsers, such as Google Chrome, Safari, Firefox, etc., are compatible with reading HTML documents. You can use any of the web browsers to display your HTML document in web format.
The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration tag is used by the web browser to understand the version of the HTML used in the document. The current version of HTML is 5 and it makes use of the following declaration −
<!DOCTYPE html>
There are many other declaration types that can be used in HTML documents, depending on what version of HTML is being used. We will see more details on this while discussing the <!DOCTYPE…> tag along with other HTML tags.
HTML Tags Vs. Elements Vs. Attributes
HTML tags are the keywords that can be used for a specific purpose to display and format the content on the webpage.
HTML elements are the basic building blocks that are made with the help of tags and content. An HTML element is created with a start tag, a content, and an end tag.
And, HTML attributes provide additional information about HTML elements; in order to define or change their behavior. Attributes are used with an opening tag.
HTML Tags Case Sensitivity
HTML tags are not case-sensitive. They can be written in uppercase or in lowercase. But the World Wide Web Consortium (W3C) recommends using lowercase tags starting from HTML 4.
Importance of HTML
HTML is the fundamental building blocks of the World Wide Web. Any page that you visit on the web contains HTML tags. HTML is important for the various reasons −
HTML defines webpage structure and helps to design websites.
With the help of CSS and JavaScript, HTML helps to create beautiful and interactive websites.
HTML helps in search engine optimization by optimizing the tags based on the targeted keywords.
HTML helps to navigate (or browse) different pages and websites from anywhere on the internet.
HTML supports user input and forms; you can easily get information from anywhere in the world (you may need background database support for it).
HTML follows an open standard by W3C. Thus, HTML supports all browsers on any type of device. You do not need to change the HTML for the different browsers or devices.
To learn HTML, you will need to study various tags and understand how they behave, while formatting a textual document. Learning HTML is simple, as users have to learn the usage of different tags in order to format the text or images to make a beautiful webpage.
jQuery simplifies JavaScript code. It reduces the JavaScript code into a single line of code. It is a fast, small, and feature-rich JavaScript library. It makes easy interaction between HTML and CSS documents, DOM, and JavaScript. jQuery is designed to simplify HTML document traversal and manipulation, event handling, animation, and Ajax with an easy-to-use API that supports multiple browsers.
Table of Content
Introduction to jQuery
jQuery Basics
jQuery Selectors
jQuery Methods
jQuery Manipulation Methods
jQuery Traversing Method
jQuery Events
jQuery Effects
jQuery Ajax Methods
jQuery Core
1. Introduction to jQuery
jQuery is a lightweight JavaScript library that is speedy, fast and concise. This library was created by John Resig in 2006.
jQuery has been designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax.
Following is the principle of the jQuery −
Separation of JavaScript and HTML: It encourages developers to completely separate JavaScript code from HTML markup.
Brevity and clarity: It promotes features like chainable functions and shorthand function names.
Eliminates of cross-browser incompatibilities: Developers does not need to worry about browser compatibility while writing code using jQuery library.
Extensibility: It means new events, elements, and methods can be easily added in jQuery library and then reused as a plug-in.
2. jQuery Basics
jQuery is a lightweight and feature-rich JavaScript library. It simplifies the overall complexity of the code by implementing the Selectors, Attributes, Events, and Effects through the use of the required API to perform the suitable task. jQuery basics
jQuery Download
There are two versions of jQuery compressed and uncompressed. The compressed version is useful for production and faster execution. Where an uncompressed version is useful for the development of easy debugging. Visit official website
jQuery selectors are tools that allow the manipulation and selection of HTML elements within a webpage. They use CSS-like syntax, making it easier to interact with and modify the DOM. Following is the jQuery selector syntax −
$(document).ready(function(){
$(selector)
});
jQuery Selectors can find HTML elements based on the following:
*: It selects all the HTML elements.
HTML element Name: It represent an HTML element name available in the DOM.
Element ID: It represents the HTML element with the id name of that element.
Element Class: It represents the HTML element with the class name of that element.
Element attribute name: It is used, to select the HTML element by its attribute name.
Element attribute value: It is used, to select the HTML element by its attribute name.
Example
Following is an example that demonstrates the use of selection and how we can use the selection in jQuery −
<!DOCTYPE html><html lang="en"><head><title>JQuery-Practice</title></head><body><h1>jQuery Selector</h1><p id="myFirstId">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</p><p class="myFirstClass">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</p><div class="firstDiv" style="border: 1px solid"><p>The first paragraph in div.</p><p>The last paragraph in div.</p></div><div id="divSecond" style='height: auto'>tutorialspoint</div></body><script src="https://code.jquery.com/jquery-3.7.1.js"></script><script>
$(document).ready(function () {
// select by element name
$("h1").css("background-color", "gray");
// select by id
$("#myFirstId").show(1000, function () {
console.log("Element is visible");
});
// select by class name
$(".myFirstClass").hide(1000);
// select by child element
$("div p:first").css("color", "red");
// select by attribute name
$(".firstDiv[style]").css("background-color", "Orange");
// select by attribute value
$("#divSecond[style='height: auto']").css({
'color': "green",
"font-size": "20px",
'padding': "10px",
'border': "2px solid black",
});
});
</script></html>
jQuery Methods
In jQuery, methods are used to set or return the DOM attributes for specific elements. The following is a list of methods with their descriptions −
Method
Description
Syntax
prop()
This method sets and return properties and values for the selected elements
$(selector).prop(parameters)
removeAttr()
This method remove attribute from the selected elements.
$(selector).removeAttr(attribute)
removeProp()
This method remove the property set by prop method.
$(selector).removeProp(property)
val()
This method return or set the value of attribute for selected element.
$(selector).val()
removeData()
This method remove data which was previously set.
$(selector).removeData(args);
data()
This method attaches or gets data for the selected elements.
$(selector).data(parameters);
height()
This method check the height of an element.
$(“selector”).height()
innerHeight()
This method check the height of an element.
$(“selector”).innerHeight()
width()
This method check the width of an element.
$(“selector”).width()
innerWidth()
This method check the inner width of an element
$(“selector”).innerWidth()
css()
This method changes the style property of the selected element.
$(selector).css(property)
addClass()
This method adds more property to the each selected element.
$(selector).css(property)
removeClass()
This method removes class name from the selected element.
This method check if the element with specified class name exists.
$(selector).hasClass(className);
toggleClass()
This method changes the class attached with selected element.
$(selector).toggleClass(class, function, switch)
scrollTop()
This method returns the vertical top position of the scrollbar.
$(selector).scrollTop(position)
scrollLeft()
This method sets and return the horizontal position of the scroll bar.
$(selector).scrollLeft(position)
Example
In the following example, we will demonstrate some of the above-listed methods and how they work in jQuery −
<!DOCTYPE html><html lang="en"><head><title>JQuery-Practice</title></head><body><h1>jQuery Selector</h1><p id="myFirstId">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</p><div class="firstDiv" style="border: 1px solid"><p>The first paragraph in div.</p><p>The last paragraph in div.</p></div><div id="divSecond" style='height: auto'>tutorialspoint</div></body><script src="https://code.jquery.com/jquery-3.7.1.js"></script><script>
$(document).ready(function () {
// apply css on h1 element
$("h1").css("background-color", "gray");
// set properties of first div
$("#myFirstId").prop("title", "This is my first paragraph");
// return the value of title property
var title = $("#myFirstId").prop("title");
console.log(title);
// remove attribute from selected element
$(".firstDiv").removeAttr("style");
// get data from divSecond
var data = $(".firstDiv").data("name");
console.log(data);
// check height of divSecond
var height = $("#divSecond").height();
console.log(height);
// check innderwidth of divSecond
var innerWidth = $("#divSecond").innerWidth();
console.log(innerWidth);
});
</script></html>
jQuery Manipulation Methods
There are different kinds of manipulation methods on jQuery that can be used to manipulate the DOM. This method can be categorized in two ways.
Setter
In the setter, there are various methods available. Some methods are designed to change the attributes of an element, while others set the type properties of the element. Additionally, there are some methods that can modify entire elements or groups of elements by allowing actions such as inserting, copying, and removing.
Getter
Several methods work as getter method, such as attr(), html(), and val(), which can be used to retrieve information from DOM elements for further use.
Insert an HTML element at the end of the selected element.
$(content).appendTo(selector)
html()
Sets or return the innerHTML content to selected element.
$(selector).html(function(index, currentcontent))
prependTo()
Insert an HTML element at the beginning of the selected element.
$(content).prepend(selector)
text()
Sets or returns the text content of the element.
$(selector).text(function(index, content))
clone()
Makes a copy of the selected elements including its child.
$(selector).clone()
insertBefore()
Insert HTML content before a specified element.
$(content).insertBefore(target)
insertAfter()
Insert HTML content after specified element.
$(content).insertAfter(target)
detach()
Remove the selected elements from the DOM tree.
$(“selector”).detach()
empty()
Remove all child node and their content for selected elements.
$(“selector”).empty()
remove()
Remove all the selected elements including the text.
$(selector).remove(property)
replaceWith()
Replace the selected element with the new one.
$(selector).replaceWith(content, function)
wrapAll()
Used to wrap specified element against all the selected elements.
$(selector).wrapAll(wrap_element)
Example
In the following example, we demonstrate the use of the manipulation method and how these methods work in jQuery −
<!DOCTYPE html><html lang="en"><head><title>JQuery-Practice</title></head><body><h1>jQuery Selector</h1><p id="myFirstId">
Lorem Ipsum is simply dummy text of the printing and typesetting industry
</p><p id="mySecondPara">This is second paragraph</p><div class="firstDiv" style="border: 1px solid"><p>The first paragraph in div.</p><p>The last paragraph in div.</p></div><div id="divSecond" style='height: auto'>tutorialspoint</div><ol><li>tutorialspoint</li></ol><button id="firstbtn">first btn</button><button id="secondbtn">second btn</button><button id="thirdbtn">third btn</button><button id="fourthbtn">insert btn</button><button id="fivethbtn">empty btn</button><button id="sixthbtn">remove btn</button></body><script src="https://code.jquery.com/jquery-3.7.1.js"></script><script>
$(document).ready(function () {
// return the inner HTML content
var content = $("#myFirstId").html();
console.log(content);
$("#firstbtn").click(function(){
// return the text content
$("#mySecondPara").text(function(){
return "changing the content of para 2";
});
})
$("#secondbtn").click(function () {
// appen the list append()
$("ol").append("<li>Append Tp</li>");
});
$("#thirdbtn").click(function () {
// prepend the list using prepend()
$("<span>jQuery Tutorialspoint</span>").prependTo("h1");
});
// insertBefore() method
$(".firstDiv").click(function(){
$("<p>Inserted before the second para</p>").insertBefore("#mySecondPara");
});
// insertAfter() method
$("#fourthbtn").click(function(){
$("<p>I am tutorialspoint</p>").insertAfter("#mySecondPara");
});
// empty() method
$("#fivethbtn").click(function(){
$(".firstDiv").empty();
});
// remove() method
$("#sixthbtn").click(function(){
$(".firstDiv").remove();
});
});
</script></html>
jQuery Traversing Method
In jQuery traversing stands for moving through or HTML element to find filter or select the particular or entire element based on the traversing. Following are the list of traversing method −
Method
Description
Syntax
children()
Finds all the child element related to selected element.
$(selector).children()
parent()
Finds the parent element related to the selected element
$(selector).parent()
next()
Returns the next sibling of the selected element.
$(selector).next()
closest()
Returns the first ancestor of the selected element in the DOM tree.
$(selector).closest(parameters);
prevUntil()
Finds all the previous sibling element between two elements.
$(selector1).nextUntil(selector2)
siblings()
Finds all the siblings elements of the selected element.
$(selector).siblings(function)
first()
Selects the first element from the specified elements.
$(selector).first()
last()
Finds the last element from the specified elements
$(selector).last()
is()
Checks one of the selected elements matches the selectorElements.
Translates all items in an array or object to a new array.
jQuery.map( array/object, callback )
filter()
Returns the elements which matches the given conditions.
$(selector).filter(criteria, function(index))
not()
Returns all elements which do not match the selected element.
$(selector).not(A)
each()
Specifies the function to run for each matched element.
$(selector).each(function(index, element))
find()
Finds all the descendent elements of selected element.
$(selector).find()
Example
Following is an example of the jQuery traversing method. Here, we demonstrate how we can use this method −
<!DOCTYPE html><html lang="en"><head><title>JQuery-Practice</title></head><body><h1>jQuery Traverse Method</h1><h3>jQuery children() Method</h3><div class="firstDiv" style="width: 500px">
This is the current element !!!
<p class="first">
This is the first paragraph element !!!
<span>This is grandchild</span></p><p class="second">
This is the second paragraph element !!!
<span>This is grandchild</span></p></div><hr /><div class="secondDiv">
This is parent element !
<p>This is first paragraph</p><span>first span box </span><h2>heading 2 !</h2><h3>jQuery next() Method</h3><p>This is the second paragraph and next sibling to h3 !</p></div><hr /><div class="main" style="width: 600px">
This is great grand parent element !
<ul>
This is the second ancestor element !
<ul>
This is first ancestor element !
<li>
This is direct parent !
<span>jQuery closest() Method</span></li></ul></ul></div><hr /><div class="main_div"><div style="width: 500px">
div (Great-Grandparent)
<ul>
This is the grand-parent of the selected span element.!
<li>
This is the parent of the selected span element.!
<span>jQuery parent() Method</span></li></ul></div></div><hr /><div style="width: 400px" class="sib1"><ul>
This is parent !!!
<li class="stop">list 1 !!!</li><li>jQuery prevUntil() Method</li><li>first list !</li><li>second list !</li><li class="start">list 5 !!!</li><li>other sibling</li><li>other sibling</li></ul></div><hr /><div class="sib2">
This is parent!!!
<p>This is paragraph!!!</p><span>This is span box!!!</span><h2>jQuery siblings() Method</h2><h3>This is heading 3!</h3></div><hr /><div id="div1" style="border: 1px solid rgb(21, 0, 128)"><p>jQuery first() Method</p></div><br /><div style="border: 1px solid rgb(21, 0, 128)"><p>This is the second statement.</p></div><br /><div id="div2" style="border: 1px solid rgb(21, 0, 128)"><p>jQuery last() Method</p></div><hr /><section id="div3"><h6 id="pid">
jQuery is() Method - Click me to find out if I my parent is a section
element.
</h6></section><hr /><ul><li id="first">jQuery filter() Method</li><li id="middle">Tutorialspoint</li><li id="last">India</li></ul><hr /><h5 id="main_content">I am Tutorialspoint.!!!</h5><h5>This is jQuery not() Method.</h5><hr /></body><script src="https://code.jquery.com/jquery-3.7.1.js"></script><script>
$(document).ready(function () {
// children()
$(".firstDiv").children("p.first").css({
color: "green",
border: "2px solid gray",
});
});
$(document).ready(function () {
// next()
$("h3").next().css({
border: "2px solid gray",
});
});
$(document).ready(function () {
// closest()
$("span").closest("ul").css({
color: "orange",
border: "2px solid red",
});
});
$(document).ready(function () {
// parent()
$("#inner").parent().css({
color: "green",
border: "2px solid green",
});
});
$(document).ready(function () {
// siblings()
$("h2").siblings().css({
color: "black",
border: "2px solid green",
});
});
$(document).ready(function () {
// first()
$("#div1").first().css("background-color", "lightgreen");
});
$(document).ready(function () {
// last()
$("#div2").last().css("background-color", "lightblue");
});
$(document).ready(function () {
// is()
$("h6").click(function () {
if ($("h6").parent().is("#div3")) {
The Events refers to the action performed by the user or visitor who visited the site during their activity with the website. An event can be a button click, mouse hover, mouse pointer movement over the image, any key pressed from the keyboard, etc. Following is the list of events −
Events
Description
Syntax
on()
Attached on or more handler to the selected elements and child elements.
Used to remove the focus from the selected element.
$(selector).blur(function)
resize()
It trigger when the browser window change the size.
$(selector).resize(function)
scroll()
Used to scroll in specified element.
$(selector).scroll(function)
load()
It loads data from the server and return them to the selected elements.
$(selector).load(URL, data, callback);
trigger()
Triggers a specified event handlers to the selected elements.
$(selector).trigger(event,parameters)
click()
Starts the click event or attached a function to return when click event occurs.
$(selector).click(function);
hover()
Specifies function to start when mouse pointer moves over selected element.
$(selector).hover(Function_in, Function_out);
mouseover()
It works when mouse pointer moves over the selected elements.
$(selector).mouseover(function)
toggle()
Checks the visibility of the selected elements to toggle.
$(selector).toggle(speed, easing, callback)
keyup()
It is used to trigger the keyup event whenever the user release a key from the keyboard.
$(selector).keyup(function)
preventDefault()
Used to prevent the default action of the selected element to occur.
event.preventDefault()
Example
In the following example, we demonstrate event methods and how they work in jQuery −
<!DOCTYPE html><html lang="en"><head><title>JQuery-Practice</title></head><body><h2>jQuery Events Method</h2><p class="firstPara">This is first Paragraph !!!</p><button id="btn1">Click me</button><button id="btn2">blured me</button><div class="parent"><p>This is parent div</p><div class="nested" tabindex="0"><p>This is nested div</p></div></div><p id="bind">Using Bind here!!!</p><button id="btn3">One Method Click me!</button><p class="secondPara">
Toggle method, I am toggling after 3 sec. Lorem ipsum dolor sit amet
consectetur adipisicing elit. At odio asperiores obcaecati necessitatibus
blanditiis facere magni voluptates eligendi, libero animi quae tenetur.
Porro reprehenderit labore temporibus voluptatum quis consectetur aliquid.
</p><button id="btn4">Click me for off!</button></body><script src="https://code.jquery.com/jquery-3.7.1.js"></script><script>
$(document).ready(function () {
// using the click method
$("#btn1").click(function () {
alert("Button 1 clicked");
});
// using the hover method
$("h2")
.hover(function () {
alert("Hovered over h2");
})
.css({ color: "blue", cursor: "pointer", backgroundColor: "yellow" });
// mouseover method
$(".firstPara").mouseover(function () {
alert("Mouse over first paragraph");
});
// using blur method
$("#btn2").blur(function () {
alert("Button 2 blured");
});
// using on method
$(".parent").on("click", function () {
alert("Parent div clicked");
});
// using focus with on method
$(".nested")
.focus(function () {
jQuery effects are pre-built visual effects animation and transitions that can be applied to HTML elements. The effects are the parts of the jQuery library that simplify the process of adding dynamic behaviour to web pages. Following is the list of jQuery effects −
Effects
Description
Syntax
hide()
It is used to hide the selected element.
$(selector).hide(duration, call_function);
show()
Used to display hidden and selected elements.
$(selector).show(speed, callback)
toggle()
Check the visibility of selected element to toggle.
$(selector).toggle(speed, callback)
animate()
Used to change the state of element with CSS style.
$(selector).animate({style}, para…)
delay()
Set a timer to delay the execution in the queue.
$(selector).delay(para1, para2);
finish()
Used to stop the animation running at present time.
$(selector).finish();
clearQueue()
Removes all items in the queue that have not yet been run.
$(selector).clearQueue(name);
dequeue()
Removes the next function from the queue and executes it.
$(selector).dequeue(name);
fadeIn()
Used to changes the opacity of the selected elements.
$(selector).fadeIn(speed, callback)
fadeOut()
Changes the level of opacity for selected element.
$(selector).fadeOut(speed, callback )
fadeTo()
Changes the opacity of the selected element.
$(selector).fadeTo(opacity, call_function)
fadeToggle()
Toggles between fadeIn and fadeOut methods.
$(selector).fadeToggle()
queue()
Used to show the queue of function to be executed.
$(selector).queue(queue_name)
stop()
Used to stop the currently running animations
$(selector).stop(stopAll, goToEnd);
Example
Following is an example of the jQuery effects methods. Here, we demonstrate and use the effects on the HTML element −
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam ut iure,
dolorem maxime, nulla recusandae ab a ipsam minima deleniti aliquid.
Corrupti, incidunt vel omnis tempora aliquid similique dicta architecto.
</p><button id="toggle">Toggle heading</button><p id="fadeIn">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque
exercitationem autem non aspernatur veniam placeat velit, deleniti odio
laudantium perspiciatis aperiam molestiae nobis nisi? Quod fuga temporibus
quasi saepe eum.
</p><p id="fadeOut">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex iure vel id
tempora minus doloremque, eveniet inventore aperiam, a dignissimos rem
quos est animi, amet magnam iusto omnis. Cupiditate, atque?
</p><div id="div1">
I am division First. Lorem ipsum dolor sit amet consectetur adipisicing
elit. Iusto rem repudiandae vel ratione quae modi et.
</div><button id="fadetoggle">FadeToggle</button><p id="slideUp"><span>Slide Up</span> Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Veritatis reiciendis similique, commodi enim consectetur, ducimus ut
expedita nostrum
</p><button id="finish">Finish Sliding up</button><p id="slideDown"><span>Slide Down</span> Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Veritatis reiciendis similique, commodi enim
consectetur, ducimus ut expedita nostrum
</p><div
id="queueDiv"
style="
width: 200px;
height: 100px;
background-color: lightgray;
margin-top: 20px;
"
><p id="queuePara">This is a queued animation example.</p></div><button id="startQueue">Start Queue</button><button id="dequeue">Dequeue</button></body><script src="https://code.jquery.com/jquery-3.7.1.js"></script><script>
$(document).ready(function () {
// using hide method
$("#hide-show").hide(3000, function () {
console.log("The paragraph is now visible");
});
// using show method
$("#hide-show").show(2000, function () {
console.log("The paragraph is now visible");
});
// using toggle method
$("#toggle").click(function () {
$("h2").toggle(2000);
});
// using fadeIn method
$("#fadeIn").fadeIn(4000, function () {
console.log("paragraph is fadded in! ");
});
// using fadeOut method
$("#fadeOut").fadeOut(4000, function () {
console.log("paragraph is fadded in! ");
});
// using fadeToggle method
$("#fadetoggle").click(function () {
$("#div1")
.fadeToggle(2000, function () {
console.log("Fade toggle is working");
})
.css({
"background-color": "blue",
color: "white",
padding: "10px",
border: "none",
"border-radius": "5px",
});
});
// using slideUp method
$("#slideUp").slideUp(3000, function () {
console.log("Sliding up");
});
// using finish method
$("#finish").click(function () {
$("#slideUp").finish(); // Immediately complete the animation
console.log("Finished sliding up");
});
// using slideDown method
$("#slideDown").slideDown(5000, function () {
console.log("Sliding down");
});
// using stop method
$("#slideDown").click(function () {
$(this).stop(); // Stop the animation
console.log("Stopped sliding down");
});
// Using dequeue method
$("#dequeue").click(function () {
$("#queueDiv").dequeue();
console.log("Dequeued the next animation step");
});
});
</script></html>
jQuery Ajax Methods
There are various methods and functions in jQuery for Ajax functionality that allow the loading of data from the server without refreshing the browser page. Ajax is used on the client side to create asynchronous web applications. Some of the jQuery AJAX methods are used to request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post. The following is the list of methods.
AJAX Methods
Description
Syntax
ajax()
Performers an Ajax request or asynchronous HTTP request.
jQuery.ajax({name:value, name:value, ⦠})
ajaxSetup()
Sets the default value for the future ajax request.
// using post method
$("#postData").click(function () {
$.post(
"https://jsonplaceholder.typicode.com/posts",
{
title: "New Post",
body: "This is the body of the post.",
userId: 1,
},
function (data) {
console.log("Post Success:", data);
$("#result").html("<p>Post Created: " + data.id + "</p>");
},
"json"
);
});
// using ajaxSetup method
$("#ajaxSetupBtn").click(function () {
$.ajaxSetup({
url: "sample.txt",
success: function (data) {
$("#result").html(data);
},
});
$.ajax();
});
});
</script></html>
jQuery Core
jQuery enables the DOM Element Methods, properties, utilities, jQuery Object, delayed Object, Callbacks Object, and others to provide functions with modifications that improve the overall interactivity of the website. Following is the list of methods −
Methods/Properties
Description
Syntax
jQuery.Deferred()
Returns the utility object with method to register multiple callbacks to queues.
jQuery.Deferred([beforeStart])
deferred.then()
Adds handlers which are called on the differed objects.
This jQuery Cheat sheet is design to help you master all the jQuery concepts. After reading or particles of this cheat sheet you can able to develop any jQuery pages. This is a handy resource that summarizes essential concepts, functions methods, and selectors in jQuery. The jQuery library is the most powerful tool that simplifies the task like DOM manipulation, event handling, animations, and Ajax calls.