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:
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
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);
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
,