css select first child element. CSS Child Selectors

  • The task being performed is the selection of child elements.
  • The notation is a chain: a simple parent selector, a ">" combinator, a simple child selector.
  • Usage example:

Let's set the left indent for the list directly nested in the element with the content class (these rules will not affect lists of the second level of nesting):

Content > ul ( margin-left: 20px; )

Learn more about the child selector

The main difference between the child selector and the one discussed earlier is the fact that if the child selector selects all descendants, regardless of the level of nesting, then the child selector selects only the first level descendants - that is, directly nested elements. For example, let's write this:

Div > span ( color: #555; /* gray color */ )

...and this code:

This text will be black. And this one is grey, because this span is a child element for div.

Again, black text. And this text is also black, since this span is not a child of a div. Its immediate parent is the p tag.

Complex and heavy web applications have become common these days. Cross-browser and easy-to-use libraries like jQuery with their wide functionality can greatly help with DOM manipulation on the fly. Therefore, it is not surprising that many developers use such libraries more often than they work with the native DOM API, which had a lot of problems. And while browser differences are still a problem, the DOM is in better shape now than it was 5-6 years ago when jQuery was gaining popularity.

In this article, I'll demonstrate the DOM's ability to manipulate HTML, focusing on parent, child, and neighbor relationships. I'll conclude with a breakdown of browser support for these features, but keep in mind that the jQuery type library is still a good option due to bugs and inconsistencies in the implementation of native functionality.

Counting child nodes

For demonstration I will use the following HTML markup, during the article we will change it several times:

  • Example one
  • example two
  • example three
  • example four
  • example five
  • Example Six

Var myList = document.getElementById("myList"); console.log(myList.children.length); // 6 console.log(myList.childElementCount); // 6

As you can see, the results are the same, although the techniques used are different. In the first case, I use the children property. This is a read-only property and returns a collection HTML elements, located inside the requested element; to count their number, I use the length property of this collection.

In the second example, I'm using the childElementCount method, which I find to be a neater and potentially more maintainable way (more on this later, I don't think you'll have trouble understanding what it does).

I could try to use childNodes.length (instead of children.length), but look at the result:

Var myList = document.getElementById("myList"); console.log(myList.childNodes.length); // 13

It returns 13 because childNodes is a collection of all nodes including spaces - keep this in mind if you care about the difference between child nodes and child element nodes.

Checking for the Existence of Child Nodes

To check if an element has child nodes, I can use the hasChildNodes() method. Method returns boolean indicating their presence or absence:

Var myList = document.getElementById("myList"); console.log(myList.hasChildNodes()); // true

I know that my list has child nodes, but I can change the HTML so that there are none; now the markup looks like this:

And here is the result of running hasChildNodes() again:

Console.log(myList.hasChildNodes()); // true

The method still returns true . Although the list does not contain any elements, it does contain a space, which is a valid node type. This method considers all nodes, not just element nodes. In order for hasChildNodes() to return false, we need to change the markup again:

And now the expected result is displayed in the console:

Console.log(myList.hasChildNodes()); // false

Of course, if I know I might encounter a space, I first check for the existence of child nodes, then use the nodeType property to determine if there are element nodes among them.

Adding and Removing Child Elements

There are techniques that can be used to add and remove elements from the DOM. The most famous of these is based on a combination of the createElement() and appendChild() methods.

VarmyEl = document.createElement("div"); document.body.appendChild(myEl);

In this case, I am creating

using the createElement() method and then adding it to the body . Very simple and you have probably used this technique before.

But instead of inserting specifically created element, I can also use appendChild() and just move the existing element. Suppose we have the following markup:

  • Example one
  • example two
  • example three
  • example four
  • example five
  • Example Six

example text

I can change the location of the list with the following code:

Var myList = document.getElementById("myList"), container = document.getElementById("c"); container.appendChild(myList);

The final DOM will look like this:

example text

  • Example one
  • example two
  • example three
  • example four
  • example five
  • Example Six

Note that the entire list has been removed from its place (above the paragraph) and then inserted after it, before the closing body . While the appendChild() method is typically used to add elements created with createElement() , it can also be used to move existing elements.

I can also completely remove a child element from the DOM with removeChild() . Here's how our list is removed from the previous example:

Var myList = document.getElementById("myList"), container = document.getElementById("c"); container.removeChild(myList);

The element has now been removed. The removeChild() method returns the removed element and I can store it in case I need it later.

Var myOldChild = document.body.removeChild(myList); document.body.appendChild(myOldChild);

There is also the ChildNode.remove() method, relatively recently added to the specification:

Var myList = document.getElementById("myList"); myList.remove();

This method does not return a remote object and does not work in IE (Edge only). And both methods remove text nodes in the same way as element nodes.

Replacing child elements

I can replace an existing child with a new one, whether or not that one exists new element or I created it from scratch. Here is the markup:

example text

Var myPar = document.getElementById("par"), myDiv = document.createElement("div"); myDiv.className = "example"; myDiv.appendChild(document.createTextNode("New element text")); document.body.replaceChild(myDiv, myPar);

New element text

As you can see, the replaceChild() method takes two arguments: the new element and the old element it replaces.

I can also use this method to move an existing element. Take a look at following html:

example text 1

example text 2

example text 3

I can replace the third paragraph with the first paragraph with the following code:

Var myPar1 = document.getElementById("par1"), myPar3 = document.getElementById("par3"); document.body.replaceChild(myPar1, myPar3);

Now the generated DOM looks like this:

example text 2

example text 1

Selecting Specific Child Elements

There are several different ways selecting a particular element. As shown earlier, I can start by using the children collection or the childNodes property. But let's look at other options:

The firstElementChild and lastElementChild properties do exactly what you would expect from their name: select the first and last child elements. Let's go back to our markup:

  • Example one
  • example two
  • example three
  • example four
  • example five
  • Example Six

I can select the first and last elements with these properties:

Var myList = document.getElementById("myList"); console.log(myList.firstElementChild.innerHTML); // "Example one" console.log(myList.lastElementChild.innerHTML); // "Example six"

I can also use the previousElementSibling and nextElementSibling properties if I want to select child elements other than the first or last. This is done by combining the firstElementChild and lastElementChild properties:

Var myList = document.getElementById("myList"); console.log(myList.firstElementChild.nextElementSibling.innerHTML); // "Example two" console.log(myList.lastElementChild.previousElementSibling.innerHTML); // "Example five"

There are also similar properties firstChild , lastChild , previousSibling , and nextSibling , but they take into account all node types, not just elements. In general, properties that consider only element nodes are more useful than those that select all nodes.

Inserting content into the DOM

I've already looked at ways to insert elements into the DOM. Let's move on to a similar topic and take a look at the new features for inserting content.

First, there's a simple insertBefore() method that's a lot like replaceChild() , takes two arguments, and works on new elements as well as existing ones. Here is the markup:

  • Example one
  • example two
  • example three
  • example four
  • example five
  • Example Six

Example Paragraph

Notice the paragraph, I'm going to remove it first and then insert it before the list, all in one fell swoop:

Var myList = document.getElementById("myList"), container = document.getElementBy("c"), myPar = document.getElementById("par"); container.insertBefore(myPar, myList);

In the resulting HTML, the paragraph will come before the list, and this is another way to wrap the element.

Example Paragraph

  • Example one
  • example two
  • example three
  • example four
  • example five
  • Example Six

Like replaceChild() , insertBefore() takes two arguments: the element to add and the element before which we want to insert it.

This method is simple. Let's try a more powerful way to insert now: the insertAdjacentHTML() method.

I think a lot of people know about contextual selectors in CSS. They are used most often, however, experienced layout designers are well aware that sometimes contextual selectors introduce certain problems. This problem is related to the fact that in the structure of an element there can be many identical elements nested inside each other. And you need to apply the style not to all nested elements, but only to the immediate child element. This is what they are used for child selectors in CSS.

To make the problem clearer, let's give a small example. Let us have such HTML code:



First paragraph



Second paragraph


And our task is to make red only " Second paragraph". If we write using the context selector:

Container p(
color: red;
}

Then both paragraphs will turn red, which we don’t need at all. This task very easy to solve with child selectors in CSS:

Container > p(
color: red;
}

That's it, now we only have red " Second paragraph". Since this particular paragraph is a direct child of .container. BUT " First paragraph" is a child of internal div, so it is not affected by the child selector.

Such tasks are so easily solved, however, there is one huge minus child selectors in CSS- they don't work in browsers Internet Explorer . For this reason, their use is highly discouraged. But if you suddenly meet somewhere, then now you will know what this type of selectors means and what it does.

You have reached the third part of this chapter. Here you will learn how to use child selectors in CSS, as well as some additional pseudo-classes for more precise selection.

CSS Child Selectors

In the previous article, we talked about family relationships between elements of an HTML document, including child elements. Let's look at an example of how these links can be used in CSS.

Imagine that you need to style only those tags

which are children of without affecting the rest

(for example,

Subsidiaries of

).
How to do it? Very simple: create a child selector:

Body > p ( color: #333; )

Note the > symbol after body . With it, you indicate that the style is applied exclusively to child tags.

parent . If the symbol is removed, then the style will be applied to absolutely all tags.

which are inside the tag , although they may not be children of it.

Additional pseudo-classes

CSS3 has a number of pseudo-classes for dealing with child elements. Below is a description of each of them, examples of usage, and differences between pseudo-classes of the form "child" and "of-type".

  • :first-child - with this pseudo-class, you can apply a style to the specified element of the web page, provided that it is first
  • :last-child - the style is applied to the specified element of the web page, provided that it is last a child of its parent;
  • :nth-child - allows you to select even (even) and odd (odd) child elements; also using this pseudo-class, you can style alternating child elements using expressions like an + b and numbers;
  • :only-child - applies to the child element, provided that it is the only a child of a parent;
  • :first-of-type - the style is applied to the first element of the specified type(even if this element is not the first child of its parent and there are other child elements of other types above it);
  • :last-of-type - works exactly like the previous pseudo-class, with the only difference that the style is applied to the last element of the specified type;
  • :nth-of-type - similar in principle to :nth-child , but focuses on type of element;
  • :only-of-type - applied to a child element of the specified type, provided that it is in the parent the only child of his type.

Usage example for :first-child, :last-child and :nth-child

First child

Second child

third child

odd number
Even number
odd number
Even number

Last child

/* CSS */ p:first-child ( font-weight: bold; text-transform: uppercase; ) p:last-child ( font-style: italic; font-size: 0.8em; ) p:nth-child( 3) ( color: red; ) tr:nth-child(odd) ( background-color: #A2DED0; ) tr:nth-child(even) ( background-color: #C8F7C5; ) Screenshot: application:first-child, :last-child and :nth-child

We have written a CSS style for the child elements of a simple HTML document, where the tag

is a parent for tags

,

. Let's take the CSS one by one.

The first rule, p:first-child, concerns the p element: if it is the first child of its parent, then a style is applied to it (in our case, it is a bold font and the text is converted to uppercase). If in the given HTML code immediately after the opening tag

add another tag (for example,

), then the p:first-child style will no longer be displayed, because

Will no longer be the first child tag. In this case, the first child will be h2 .

The same thing happens with the p:last-child rule - the CSS style will be applied to the tag

Only when he appears the last child of its parent. Add after

Any other tag of a different type and you will see the p:last-child rule no longer apply.

The p:nth-child(3) rule works for third child tag

(this is indicated by the number 3 in brackets). The font color for this paragraph becomes red. You can change the number 3 (for example, to 2) and see the result.

The tr:nth-child(odd) and tr:nth-child(even) rules work for odd and even tr elements, respectively. You can see the result in the screenshot, as well as copy all the code and experiment with the styles yourself.

Usage example: first-of-type, :last-of-type, :nth-of-type and :only-of-type

First child

Second child

third child

fourth child

Fifth child

Last child

/* CSS */ p:first-of-type ( color: violet; text-transform: uppercase; ) p:last-of-type ( font-style: italic; font-size: 0.8em; ) p:nth- of-type(3) ( color: red; ) p:nth-of-type(odd) ( background-color: #A2DED0; ) p:nth-of-type(even) ( background-color: #C8F7C5; ) h3:only-of-type ( text-decoration: underline; )
Screenshot: applying :first-of-type, :last-of-type, :nth-of-type and :only-of-type

First css rule, which you see is p:first-of-type . What does it do? It selects a child element of type p that first meets the parent. And it doesn't matter where this tag is located among elements of other types - on the first, second or tenth. This is the difference between the :first-child and :first-of-type pseudo-classes.

The second rule, p:last-of-type, applies the style to last child element of type p . As you can see from the HTML code, after the last tag

There is also a tag

, the presence of which does not affect the execution of the CSS rule in any way (unlike the :last-of-child option).

The next rule, p:nth-of-type(3), changes the font color to red. Apply this style to the tag

Which is third by an element of its type in the parent. In the screenshot you can see that the red color is applied to the tag

Which in fact is the fifth child of the tag

. But if you do not take into account elements of other types, then it turns out that the tag

With a red font, it is in third place (among the tags of its type). This is how this rule works.

The rules p:nth-of-type(even) and p:nth-of-type(odd) work similarly: since the name p is given before the colon, the even and odd child elements of type p are selected and colored with the given colors. The rest of the elements are skipped.

The last rule - h3:only-of-type - applies to the content of the tag

, making the text underlined. This style only works because the tag

is the only child element of its type. If you add another tag to the HTML code

, the style will not be applied.

conclusions

The CSS child selector allows you to change the style of a child element in an HTML document based on who its parent is.

With the help of additional pseudo-classes: first-child, :last-child, :nth-child, :only-child, you can style the child elements of an HTML document, focusing on their location, numbering in the element tree.

Pseudo-classes :first-of-type, :last-of-type, :nth-of-type, :only-of-type allow you to style child elements of an HTML document based on their type, as well as numbering in the element tree .

The main purpose of this selector follows from its name and is to refer to the child element. Displayed using the elementary ">" sign, which links the child element to the parent element. It is also worth noting that simple selectors are used in circulation. As an example, consider the following encoding:

Element > ul ( padding-top: 20px; )

This encoding means that the list nested in element will have an inner padding of 20 pixels from the top. The presence of the ">" sign in this entry indicates that the rule will apply only to lists of the first level of nesting.

A detailed analysis of how the child selector works

The child element selector has similar properties to the child selector. However, there is a characteristic feature that shows the fundamental difference between these operations. It lies in the fact that the influence of the descendant selector extends to absolutely all elements, while the child selector subordinates the styles of the positions of the first level of classifications.

The following example will help you better understand the work of the child selector operator:

Div > p ( color: #ff0000; /* red */ )

< div> Given line will default to black text.< span>This line is recolored in red due to the fact that p is a child tag for the div. < p>Again we see black letters.< span>Here we also see black symbols, since the p tag is the parent for this span.

This example confirms the operation of the child selector operator according to the degree of nesting.

Restriction for applying child selector operator

It is worth noting that this operation supported by all browsers except the legendary Internet Explorer 6. I think few people use this browser, however, if there are such unique ones, then for them there is a way out of the situation, which will be described in a separate article.

Why is it used

Programmers refer to child element selectors when they need to assign their own unique style to nested elements. Also, using this selector can reduce the amount of CSS, which will improve the readability of the document. As practice shows, this operation is most often used when creating drop-down menus.

Also, the child element selector is used to assign unique styles to elements whose parents are already known in advance. In other words:

Main > header( /* styling only applies to the main header */ }

This example is valid in cases where the header tag is used to highlight the headings of articles. In our case, we set the design only for the main header, and do not touch the secondary ones. This technique also avoids the use of unnecessary identifiers, which in turn lightens the weight of the CSS file and makes it more readable.

Summing up

Thus, the child element operator can be used not only to design drop-down menus, but also to slightly optimize your Internet resource for the work of search robots.

Internet