HTML DOM Span Object: Accessing and Manipulating <span>
Elements
The HTML DOM span
object represents the <span>
element in HTML. The <span>
tag is an inline container used to group elements for styling or scripting purposes. Unlike block-level elements, <span>
elements do not create line breaks before or after their content, making them ideal for inline styling and text manipulations. In this article, we’ll explore how to access and manipulate <span>
elements using the HTML DOM in JavaScript.
What is the HTML <span>
Element?
The <span>
element is a versatile inline container. It’s a generic tag that you can use to:
- Apply styles to specific parts of text.
- Target specific inline elements using JavaScript.
- Group inline elements to apply transformations.
- Isolate sections of text or other inline content.
Unlike block-level elements like <div>
or <p>
, the <span>
tag does not force line breaks before or after the content it wraps.
Accessing <span>
Elements
To work with <span>
elements, you need to access them using JavaScript via the Document Object Model (DOM). You can use methods like getElementById
, getElementsByTagName
, getElementsByClassName
, or querySelector
and querySelectorAll
.
Using getElementById
If your <span>
element has a unique id
attribute, you can easily retrieve it using document.getElementById()
.
<p>
This is a <span id="mySpan1" style="color: blue;">span</span> element.
</p>
<script>
const spanElement1 = document.getElementById("mySpan1");
console.log("Span Element:", spanElement1);
console.log("Span text Content:", spanElement1.textContent);
spanElement1.style.fontWeight = "bold";
</script>
Output
Span Element: <span id="mySpan1" style="color: blue;">β¦</span>
Span text Content: span
In the code above, we access the <span>
element with the ID “mySpan1” and log its content and the element itself. We then bold the content of the span
.
Using getElementsByTagName
To access multiple <span>
elements, use document.getElementsByTagName('span')
. This method returns an HTMLCollection, which you can iterate through.
<p>
This is
<span style="color: red;">one</span>
span, and this is
<span style="color: green;">another</span> span.
</p>
<script>
const spanElements2 = document.getElementsByTagName("span");
console.log("Span elements: ", spanElements2);
for (let i = 0; i < spanElements2.length; i++) {
spanElements2[i].style.textDecoration = "underline";
}
</script>
Output
Span elements: HTMLCollection(2) [span, span]
This code retrieves all <span>
elements in the document and applies an underline decoration to each one.
Using getElementsByClassName
If your <span>
elements share a common class name, you can use document.getElementsByClassName()
to access them.
<p>
This is a
<span class="mySpanClass" style="color: purple;">span</span>
with a class. And here is
<span class="mySpanClass" style="color: orange;">another</span> one.
</p>
<script>
const spanElements3 = document.getElementsByClassName("mySpanClass");
console.log("Span elements:", spanElements3);
for (let i = 0; i < spanElements3.length; i++) {
spanElements3[i].style.fontStyle = "italic";
}
</script>
Output
Span elements: HTMLCollection(2) [span.mySpanClass, span.mySpanClass]
This code fetches all <span>
elements with the class name “mySpanClass” and applies italics to each element.
Using querySelector
and querySelectorAll
The querySelector
and querySelectorAll
methods provide more flexible ways to select elements using CSS selectors.
<div id="container4">
<p>
This is <span class="targetSpan" style="background-color: yellow;"
>targeted span</span
> element.
</p>
<p>
And this is <span class="targetSpan" style="background-color: lightblue;">another span</span> element
</p>
</div>
<script>
const spanElement4_1 = document.querySelector("#container4 .targetSpan");
console.log("Selected Span Element using querySelector:", spanElement4_1);
spanElement4_1.style.border = "2px solid black";
const spanElements4_2 = document.querySelectorAll("#container4 .targetSpan");
console.log("Selected Span Elements using querySelectorAll:", spanElements4_2);
spanElements4_2.forEach(element => {
element.style.padding = '5px';
});
</script>
Output
Selected Span Element using querySelector: <span class="targetSpan" style="background-color: yellow;">β¦</span>
Selected Span Elements using querySelectorAll: NodeList(2) [span.targetSpan, span.targetSpan]
The querySelector
selects the first element that matches the provided selector, and querySelectorAll
selects all matching elements, returning a NodeList which you can iterate through.
Key Properties and Methods of the Span Object
The span
object in the DOM provides various properties and methods that can be used to interact with <span>
elements.
Property/Method | Type | Description |
---|---|---|
`id` | String | Gets or sets the ID of the span element. |
`className` | String | Gets or sets the class name of the span element. |
`innerHTML` | String | Gets or sets the HTML content within the span element. |
`textContent` | String | Gets or sets the text content of the span element. |
`style` | Object | Gets or sets the inline style of the span element. |
`setAttribute(name, value)` | Function | Sets the value of an attribute. |
`getAttribute(name)` | Function | Returns the value of the specified attribute. |
`classList` | DOMTokenList | Provides methods to add, remove, and toggle CSS classes of the span element. |
`addEventListener(event, function)` | Function | Attaches an event handler to the span element. |
Examples of Span Manipulations
Letβs explore some practical examples to manipulate the <span>
elements:
Changing Content and Style
<p>
Change this <span id="mySpan5">original</span> content using Javascript.
</p>
<button id="changeSpanButton">Change Span</button>
<script>
const spanElement5 = document.getElementById("mySpan5");
const button5 = document.getElementById("changeSpanButton");
button5.addEventListener('click', () =>{
spanElement5.textContent = "new text content!";
spanElement5.style.color = "red";
spanElement5.style.fontWeight = "bold";
})
</script>
This code changes the text content of the span and also applies style changes when a button is clicked.
Adding and Removing Classes
<p>
This <span id="mySpan6" class="initial-span">span</span> has class that is going to be toggled.
</p>
<button id="toggleSpanClass">Toggle Span Class</button>
<script>
const spanElement6 = document.getElementById("mySpan6");
const button6 = document.getElementById('toggleSpanClass');
button6.addEventListener('click', ()=>{
spanElement6.classList.toggle("active-span");
})
</script>
<style>
.initial-span{
font-style: italic;
}
.active-span{
background-color: lightblue;
padding: 5px;
}
</style>
Here we toggle a class named active-span
using the classList
property when the button is clicked.
Event Handling
<p>
This is a
<span id="mySpan7" style="cursor: pointer; border-bottom: 1px dashed;">clickable span</span>.
</p>
<script>
const spanElement7 = document.getElementById("mySpan7");
spanElement7.addEventListener("click", function () {
alert("Span Clicked!");
});
</script>
In this example, we attach a click event handler to the <span>
element. When the <span>
element is clicked, an alert box is shown.
Setting and Getting Attributes
<p>
This <span id="mySpan8" data-info="example-data" style="color: brown;">span</span> has custom data attribute
</p>
<script>
const spanElement8 = document.getElementById('mySpan8');
const dataInfo = spanElement8.getAttribute('data-info');
console.log("Data Attribute Value: ", dataInfo);
spanElement8.setAttribute("title", "This is a span element");
console.log('Title Attribute of Span: ', spanElement8.getAttribute("title"));
</script>
Output
Data Attribute Value: example-data
Title Attribute of Span: This is a span element
This code retrieves the value of custom attribute data-info
and then sets a new title
attribute for the span
.
Real-World Applications
The <span>
element and its DOM object are commonly used for:
- Text Highlighting: Highlighting specific words or phrases in a paragraph.
- Tooltips: Creating tooltips that appear when hovering over text.
- Interactive Text: Making text segments clickable or interactive.
- Dynamic Styling: Applying dynamic styling to specific parts of text based on user interactions or application state.
Browser Support
The <span>
element and its DOM object are fully supported by all modern browsers. π
Conclusion
The HTML DOM span
object provides essential functionality for accessing and manipulating <span>
elements in web development. You can use it for basic styling, dynamic content updates, and interactive text elements. Understanding how to effectively use the span
object will greatly enhance your ability to create dynamic and engaging web applications. This guide provides a strong foundation for working with span
elements in the DOM.