<span> Tag in HTML

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

The <span> HTML element is a general inline container for expressing text that does not represent anything inherently. It can be used to style elements by grouping them together (through the class or id properties) or because they share the same attribute values, such as lang. It should only be used if no alternative semantic element is available. The <span> element is similar to the <div> element, except the <div> element is a block-level element, whereas the <span> element is an inline element.

Syntax:

Example:

Output:

span tag

What is the Span Tag Used for?

  • The span tag is similar to a div in that it is used to combine comparable information so that it can all be styled together.
  • However, span differs from div because it is an inline element rather than a block element.

Note: Until you style the span tag, it has no effect on its content. The span tag is mainly used for styling and altering specific text with JavaScript.

Attributes

Global Attributes

Global attributes are properties that are shared by all HTML elements; they can be applied to all elements. They are said to be global because they are supported by both standard and non-standard HTML elements. However, they may have no effect on some.

All HTML elements, even those not specified in the standard, can have global properties. This means that any non-standard elements must nevertheless allow certain characteristics, even if using such elements renders the content non-HTML5 compliant. HTML5-compliant browsers, for example, hide content tagged as <foo hidden>...</foo>, despite the fact that <foo> is not a legitimate HTML element.

List of Global Attributes

AttributeValueDescription
accesskeyshortcut keyIt gives a tip for creating a keyboard shortcut for the currently selected element. This property is a list of characters separated by spaces. The browser should use the first one on the computer keyboard layout.
autocapitalizeoff / none, on / sentences, words, charactersControls whether and how text input is capitalized automatically when it is entered/edited by the user.
autofocusfalseIndicates that an element will be focused on page load or when the <dialogue> in which it is included is displayed.
classclassnameIt is a list of the element's classes, separated by spaces. Classes enable CSS and JavaScript to identify and access certain components using class selectors or functions.
contenteditabletrue/falseAn enumerated attribute that indicates whether or not the element should be adjustable by the user. If this is the case, the browser adjusts its widget to allow modification.
contextmenumenu-idA context menu for an element is specified. A context menu opens when the user clicks the right mouse button on an element.
data-dataForms a class of attributes known as custom data attributes, which allow private information to be exchanged between HTML and its DOM representation, which scripts can exploit. All such custom data is accessible through the HTMLElement interface of the element on which the attribute is set.
dirltr / rtl / autoSpecifies the base direction of directionality of the element's text.
draggabletrue / false / autoAn enumerated attribute indicates whether the element may be dragged with the Drag and Drop API.
dropzonecopy / move / linkWhen dragged data is dumped, this property specifies whether it is copied, relocated or linked.
enterkeyhintThis value indicates the action label (or icon) on virtual keyboards to display the enter key.
exportpartsIt is used to export shadow components from a nested shadow tree into a contained light tree transitively.
hiddenhiddenA Boolean attribute specifies whether or not the element is still relevant. For example, It can be used to conceal elements of the website that cannot be accessed until the login process is completed. The browser will not render such items.
IdnameDefines a unique identifier (ID) that must be unique throughout the document. It serves to identify the element when linking (through a fragment identifier), scripting, or styling (with CSS).
langlanguage-codeSpecifies the primary language for the text content of the element.
Spellchecktrue / falseSpecifies whether or not the element should be checked for spelling mistakes.
tabindexnumberSpecifies an element's tabbing order.
titletextIt contains text that represents advisory information about the element to which it belongs. Such information is typically, but not always, displayed to the user in the form of a tooltip.
slotAn element having a slot attribute is assigned to the slot established by the <slot> element whose name attribute matches the value of that slot attribute.
StylestyleStyle is used to add inline CSS to the currently selected element. It is recommended that styles be defined in a separate file or files. This attribute and the <style> element are primarily intended for rapid stylings, such as for testing reasons.
translateyes / noIt specifies whether or not the element's content should be translated when the page is localized.
xmllanguage-codeIn XHTML documents, it specifies the primary language for the element's text content.

Event Attributes

When a browser reacts to user behavior, it is referred to as an event. For example, if you click the submit button, the browser will display an information box. There are numerous event attributes available in HTML5 that can be activated using a computer language such as JavaScript.

The event attributes are mainly observers that can be added to any HTML tag to observe any specific event. When that event occurs with respect to that specific HTML tag for which the event attribute is specified, this attribute will execute the function of the Javascript expression associated with it.

There are a few Event attribute types, which are dependent on the event kinds allowed by JavaScript. They are as follows:

  • Window Event Attributes
  • Keyboard Event Attributes
  • Form Event Attributes
  • ClipBoard Event Attributes
  • Media Event Attributes
  • Mouse Event Attributes
  • Drag Event Attributes

Let us go over each of the categories listed above in detail one by one.

Window Event Attributes Window Events are events that are associated with the window object and apply to the HTML tag.

AttributeValueDescription
onafterprintscriptExecutes the script after the file is printed.
onbeforeprintscriptExecutes the script before the file is printed.
onbeforeunloadscriptExecutes the script before a file is unloaded.
onerrorscriptExecutes the script when an error occurs.
onhashchangescriptExecutes the script when the anchor element in the URL of the website is changed.
onloadscriptExecutes the script when the website is completely loaded.
onmessagescriptExecutes the script when a message event occurs.
onofflinescriptExecutes the script when the community connection is disconnected, and the browser starts running offline.
ononlinescriptExecutes the script when the browser starts running online.
onpagehidescriptExecutes the script when the modern website is hidden, such as though the consumer has moved away from the current website.
onpageshowscriptExecutes the script when the modern website is focused.
onpopstatescriptExecutes the script when the window's lively records are changed.
onresizescriptExecutes the script while the window is resized.
onstoragescriptExecutes the script while updating the web storage.
onunloadscriptExecutes the script while the current website is unloaded or the window is closed.

Keyboard Event Attributes Keyboard Events are those that happen when a user interacts with the keyboard.

AttributeValueDescription
onkeydownscriptThis event occurs when a user is pressing a key.
onkeypressscriptThis event occurs when a user presses a key.
onkeyupscriptThis event occurs when a user releases a key.

Form Event Attributes Form Events are HTML events that occur when a user interacts with form controls.

AttributeValueDescription
onblurscriptThis function is executed when the element loses attention.
onchangescriptThis event occurs when the element's value is modified.
oncontextmenuscriptThis script is performed when a context menu is executed.
onfocusscriptThis event occurs when the element is focused
oninputscriptThis script is executed when an element receives user input.
oninvalidscriptThis script is executed when an element is invalid.
onresetscriptThis event occurs when a form's Reset button is clicked.
onsearchscriptThis event occurs when a user types something into a search form (for input="search">).
onselectscriptExecutes when some text in an element is selected.
onsubmitscriptExecutes when some text in an element is selected. 

ClipBoard Event Attributes ClipBoard Events are events that occur when the clipboard is modified, such as copy, cut, and paste.

AttributeValueDescription
oncopyscriptThis event occurs when the user copies the content of an element.
oncutscriptThis event occurs when the user cuts the content of an element.
onpastescriptThis event occurs when the user pastes some content in an element.

Media Event Attributes Media Events are events that occur during the handling of media elements embedded within HTML documents, such as the <audio>, <video>, and <embed> tags.

AttributeValueDescription
onabortscriptScript to be executed on abort.
oncanplayscriptScript to be executed when a file is ready to play (when it has buffered enough to begin)
oncanplaythroughscriptScript that will be executed when a file can be played all the way through without halting for buffering.
oncuechangescriptScript that will be executed when the cue changes in an <track> element.
ondurationchangescriptScript that will be executed when the length of the media changes.
onemptiedscriptScript that will be executed when anything bad happens and the file becomes abruptly unavailable. (like unexpectedly disconnects)
onendedscriptScript that will be executed when the media has reached its conclusion (a useful event for messages like "thanks for listening")
onerrorscriptScript that will be executed if an error occurs while loading the file.
onloadeddatascriptScript to be executed when media data is received.
onloadedmetadatascriptScript that will be executed when meta data (such as dimensions and duration) are loaded.
onloadstartscriptExecute this script just as the file begins to load before anything is loaded.
onpausescriptScript that will be executed when the media is paused, either manually or automatically.
onplayscriptScript to be executed when the media is ready to start playing.
onplayingscriptScript that will be executed once the media has started playing.
onprogressscriptScript that will be executed while the browser is retrieving media data.
onratechangescriptScript that will be executed whenever the playback rate changes (for example, when the user selects slow motion or fast forward mode)
onseekedscriptScript that will be executed when the seeking property is set to false. It denotes that the search has come to an end.
onseekingscriptScript to be executed when the seeking attribute is set to true. It indicates that seeking is active.
onstalledscriptScript to be executed when the browser is unable to retrieve the media data for whatever reason.
onsuspendscriptScript that is supposed to be executed when requesting the media data is interrupted before it is completely loaded for whatever reason.
ontimeupdatescriptScript that will be executed when the playing position changes (like when the user skips to a different part of the video)
onvolumechangescriptScript that will be executed each time the volume is altered (includes setting the volume to "mute")
onwaitingscriptScript that will be executed when the media has been halted but is expected to resume (like when the media pauses to allow more data to be buffered)

Mouse Event Attributes

Mouse events are those that occur when a user interacts with a pointing device, such as a mouse.

AttributeValueDescription
onclickscriptThis event occurs when the mouse clicks on the element.
ondblclickscriptThis event occurs when the mouse double-clicks on the element.
onmousedownscriptExecutes when the mouse button is pressed on the element.
onmousemovescriptThis event occurs when the mouse pointer hovers over an element.
onmouseoutscriptThis event occurs when the mouse moves outside the element.
onmouseoverscriptThis event occurs when the mouse moves over the element.
onmouseupscriptExecutes when the mouse button is released.
onmousewheelscriptDeprecated. Make use of the onwheel attribute.
onwheelscriptThis event occurs when the mouse wheel rolls up or down on the element.

Drag Event Attributes

Drag events are fired every few hundred milliseconds as a user drags an element or text selection.

AttributeValueDescription
ondragscriptThis event occurs when an element is dragged.
ondragendscriptScript to be executed after the completion of a drag operation.
ondragenterscriptThis script is executed when an element is dragged to a proper drop target.
ondragleavescriptThis script is executed when an element exits a valid drop target.
ondragoverscriptThis script is executed when an element is dragged over a valid drop target.
ondragstartscriptScript that is executed at the start of a drag operation.
ondropscriptScript that will be executed when a dragged element is dropped.
onscrollscriptScript that will be executed when an element's scrollbar is scrolled.

Misc Event Attributes

AttributeValueDescription
ontogglescriptThis event occurs when the user opens or closes the <details> element.

Examples

Example 1: In this example, we will simply use the span tag with style in HTML.

Output:

span tag with style in html

Example 2: As we all know, span is an inline tag that takes up as much space as necessary while leaving room for other elements. Because each tag occupies only the necessary space and leaves the rest of the space free for subsequent components, all four-span elements will appear in the same line.

Output:

coding is awesome

Example 3: In this example, we will use the span tag to modify the background color of the text.

Output: span tag with green background color

Example 4: In this example, we will use the span tag to modify the font style of the text.

Output:

span tag with italic font style

Example 5: In this example, we will manipulate javascript with a span tag. We are going to insert a span tag within a paragraph with the id="demo" and change its text using javascript, "Scaler Academy" will be changed to "Scaler by Interview Bit!!!" after clicking on the Button.

Output:

what is span tag

Output of the above code after clicking on the "Change Text!" button:

generic inline container

Browser Support

The following browsers support the <span> tag:

  • Google Chrome
  • Internet Explorer
  • Edge 12 and above
  • Firefox 1 and above
  • Opera
  • Safari
TagSyntaxDescription
div<div>.....</div> The div tag inserts a line break and, by default, divides the text that follows the tag as it begins and until the tag ends with </div>. The div tag produces distinct boxes or containers for any components contained within it, such as text, images, and paragraphs.
article<article>.....</article> The <article> tag is a self-completed tag that can be used for any of the reasons where the <section> tag is required, plus the <article> tag independently places the content. Any social post, magazine article, blog, list of related articles, or independent content can be placed using the article tag.
section<section>.....</section>When you simply want to design any information on your website, such as adding some functionalities, you can use the <section> tag, which can alternatively be replaced by the <div> tag. When the content of a web page is appropriate for the contents outline and browsers do not pay attention to the outlines, the section tag will be useful.
nav<nav>.....</nav>In HTML pages, the <nav> tag is used to declare the navigational section. Websites often feature sections dedicated to navigational links, allowing users to browse the site. These links can be contained within a nav tag.

Conclusion

  • In this tutorial, we have covered how to alter a specific piece of text using CSS and JavaScript by surrounding it in a span tag and assigning it a unique class or id property.
  • It would be good to use classes for styling and ids for JavaScript manipulation to avoid confusion.