23.07.2020

Child selectors in CSS. Child selectors css second child


The main purpose of this selector follows from its name and is to refer to a child element. It is displayed using the simple ">" sign that links a child element to a parent element. It is also worth noting that the call uses simple selectors. As an example, consider the following encoding:

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

This encoding means that the list, which is nested in element, will be padded 20 pixels from the top edge. The presence of the ">" icon in this entry indicates that the rule will apply only to lists of the first nesting level.

Detailed analysis of how the child selector works

A child element selector has properties similar to that of a 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 child 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 to more clearly evaluate the operation of the child selector operator:

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

< div> This line will have black text by default.< span>This line turns red because p is a child tag for the div. < p>Again we see black letters.< span>Here we also see black characters, since for this span the parent is the p tag.

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

Restriction on the use of the operator of the child selector

It should be noted that this operation is supported by all browsers except for the legendary Internet Explorer 6. I think very few people use given 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 increase the readability of the document. As practice shows, this operation is most often referred to when creating drop-down menus.

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

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

This example is true 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 affect the secondary ones. This technique also avoids unnecessary use of identifiers, which in turn makes the CSS file lighter and more readable.

Summing up

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

Complex and heavy web applications are common these days. Cross-browser and easy-to-use libraries like jQuery, with their rich functionality, can greatly assist in manipulating the DOM on the fly. Therefore, it is not surprising that many developers use such libraries more often than they work with the native DOM API, with which there were many 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 will demonstrate the DOM's HTML manipulation capabilities, focusing on parent, child, and sibling relationships. In conclusion, I will give data on support for these features in browsers, but keep in mind that a library like jQuery is still a good option due to bugs and inconsistencies in the implementation of native functionality.

Counting child nodes

I will use the following HTML markup for demonstration, and we will change it several times over the course of this article:

  • 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 are different. In the first case, I am using the children property. This property is read-only and returns the collection of HTML elements that are within 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 seems to me to be a neater and potentially more maintainable way (we'll discuss this in more detail later, I don't think you'll have any problems 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 - consider this 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. The method returns boolean reporting their presence or absence:

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

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

And here is the result of a fresh run of hasChildNodes ():

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. For hasChildNodes () to return false, we need to change the markup again:

And now the expected output is printed to the console:

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

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

Adding and removing children

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.

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

In this case, I create

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

But instead of inserting a specially crafted 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 resulting 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. Although the appendChild () method is usually used to add elements created with createElement (), it can also be used to move existing elements.

I can also completely remove the child from the DOM using 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 item has now been removed. The removeChild () method returns the removed item and I can save it in case I need it later.

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

So there is the ChildNode.remove () method, which was relatively recently added to the spec:

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

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

Replacing children

I can replace the existing child with a new one, regardless of whether this new element exists or I created it from scratch. Here's 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 item. Take a look at the 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

Fetching specific children

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

The firstElementChild and lastElementChild properties do exactly what their name suggests: they 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 using 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 types of nodes, not just elements. As a rule, 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 related topic and take a look at the new content insertion options.

First, there is a simple insertBefore () method, which is a lot like replaceChild (), accepts two arguments and at the same time works with both new elements and existing ones. Here's 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 be 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 now more powerful way inserts: the insertAdjacentHTML () method.

Description

The: nth-child pseudo-class is used to style elements based on the numbering in the element tree.

Syntax

element: nth-child (odd | even |<число> | <выражение>) {...}

The values

odd All odd element numbers. even All even element numbers. number The ordinal number of the child relative to its parent. Numbering starts at 1, this will be the first item in the list. expression Specified as an + b, where a and b are integers and n is a counter that automatically takes the value 0, 1, 2 ...

If a is equal to zero, then it is not written and the record is shortened to b. If b is equal to zero, then it is also not specified and the expression is written in the form an. a and b can be negative numbers, in which case the plus sign changes to minus, for example: 5n-1.

By using negative values ​​for a and b, some results can also be negative or zero. However, items are only affected by positive values ​​due to the fact that item numbering starts at 1.

Table 1 shows some possible expressions and keywords, and also indicated which item numbers will be involved.

HTML5 CSS3 IE Cr Op Sa Fx

nth-child

21342135 213621372138
Oil1634 627457
Gold469 725647
Wood773 793486
Stones2334 8853103

V this example The: nth-child pseudo-class is used to change the style of the first row of the table, as well as to colorize all even-numbered rows (Figure 1).

Child elements are elements that sit directly within the parent element. Pay attention to the words: directly inside.

Let's take a look at a simple html code example:

Child elements.

The paragraph and in it fatty element, and behold inclined element.

Here fatty and underlined and oblique elements.

This code contains two paragraphs. Inline elements are located inside paragraphs , and ... In the second paragraph, the tag nested within a tag .

Now let's add CSS styles to this html code using child selectors.

The syntax for child selectors is:

Selector 1> Selector 2 (Property: value;)

Here's the updated code:

Child elements.

The paragraph and in it fatty element, and behold inclined element.

Here fatty and underlined and oblique elements.

So, remember: a child element is an element nested directly within the parent. That is, the child is a first-level descendant. Let's pay attention to the tag , in the first paragraph it is nested within the tag

And in the second, it is nested in the tag although it is also a descendant of the tag

Therefore, in the second paragraph of CSS, the rule for the child selector p> i (color: blue;) will not work - the italic text of the second paragraph will not be displayed in blue.

Figure 1. Work of example # 1.

Get to html element the second paragraph can be done using the CSS rule: p> u> i (color: blue;).

Let's use this rule to set the italic text of the second paragraph to yellow.

Child elements.

The paragraph and in it fatty element, and behold inclined element.

Here fatty and underlined and oblique elements.

This style will work and the italic text in the second paragraph will be displayed in yellow.

Figure 2. Work of example # 2.

A more complex example

We have html code:

Child elements.

By default, it is interpreted like this:

Problem: at CSS help turn this list into a horizontal menu.


Figure 3. Purpose of transformation.

Here's a solution to this problem using child selectors:

Child elements.

For a better understanding of this example, read on.


2021
maccase.ru - Android. Brands. Iron. news