Wrapping and grouping HTML elements

By SAGAR on 07 Apr 2021

Sometimes you want to put HTML elements in groups, or put a wrapper around certain text so that you can select it. Learn how in this article…

What is wrapping?

Wrapping is where you wrap a certain bit of text or element in a wrapper element.

What is grouping?

Grouping is where you put a wrapper around multiple elements.

Syntax - DIV

div stands for division, and is used to group elements together. Here is an example:

Syntax - SPAN

span's are generally used to wrap around certain bits of text (I will go into why further down). The syntax is as follows:

Use cases (and why?)

First of all, why would you actually want to do this in the first place? Well, there are many good reasons:

1. Make your code logical and readable - Div

By putting parts of your code into groups. Take this example:

If you were looking at this code, it would be very confusing to work out what was the content and what was other stuff. If we did this, it would make the code much more clear:

2. Style multiple elements at once - div

Chances are, you probably haven’t learned CSS yet but down the track this will be a big benefit. Let’s say you have a bunch of random elements:

What if we wanted to give all of those elements a color of blue ? (NOTE: You don’t need remember anything about CSS from this, I’m just using it to explain my point). You would have to do it like this:

In addition, this would also style any other h1, h2, etc. on the page. However, we put all these elements in a group though, it becomes much easier:

This will make all the elements inside div class="style-me" blue.

3. Position groups of elements - div

For example, let’s say you want to have a sidebar - instead of manually positioning all the elements of the sidebar, you can just wrap them with a div and position that. Consider a div as a box - when you move a box, you end up moving the stuff in it as well. If we want to move our sidebar box over to the right, doing so will also move all the stuff inside it.

4. Select content that is not selectable - span

Let’s say you have the following HTML:

What if you wanted to do something with the word awesome ? Let’s say make it red? There is no way to select it, it is just text. To select it, we can wrap it in a span with a class: