CSS: child selectors. Contextual CSS selector
Vlad Merzhevich
A child element is an element that is directly located inside a parent element. To better understand the relationships between document elements, let's look at a little code (example 12.1).
Example 12.1. Nesting of elements in a document
HTML5 CSS 2.1 IE Cr Op Sa Fx
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.
Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
IN in this example Several containers are used, which are located one inside the other in the code. This can be seen more clearly in the tree of elements, which is the name given to the structure of relationships between document tags (Fig. 12.1).
Rice. 12.1. Example element tree
In Fig. Figure 12.1 presents the nesting of elements and their hierarchy in a convenient form. Here the child element of the tag
However, the tag is not a child of the tag Let's return now to selectors. A child selector is one that is located directly inside the parent element in the element tree. The syntax for using such selectors is as follows. Selector 1 > Selector 2 (Description of style rules) The style is applied to Selector 2, but only in in that case if it is a child of Selector 1. If we refer again to Example 12.1, the view style P > EM ( color: red ) will be set to the first document paragraph, since tag is inside the container And it won't give any result for the second paragraph. And all because the tag in the second paragraph is located in a container , therefore the nesting condition is violated. In their logic, child selectors are similar to context selectors. The difference between them is as follows. A child selector is only styled if it is a direct child, that is, directly inside the parent element. For a context selector, any level of nesting is allowed. To make it clear what we're talking about, let's look at the following code (example 12.2). Example 12.2. Contextual and child selectors HTML5 CSS 2.1 IE Cr Op Sa Fx
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna Aliguam erat volutpat. The result of this example is shown in Fig. 12.2. Rice. 12.2. Text color set using a child selector To tag In the example, two rules operate simultaneously: context selector (tag located inside ). In this case, the rules are equivalent, since all the conditions for them are met and do not contradict each other. In such cases, the style shown in the code below is applied, so the italic text appears in red. If you reverse the rules and put DIV I below, the text color will change from red to green. Note that in most cases you can avoid adding child selectors by replacing them with context selectors. However, the use of child selectors expands the ability to control element styles, which ultimately allows you to get desired result, as well as simple and clear code. It is most convenient to use these selectors for elements that have a hierarchical structure - this includes, for example, tables and various lists. Example 12.3 shows changing the appearance of a list using styles. By nesting one list into another we get a type of menu. In this case, the headings are located horizontally, and the set of links is located vertically under the headings (Fig. 12.3). Rice. 12.3. List as a menu To position text horizontally, add a style to the LI selector float property. In order to separate the style of a horizontal and vertical list, child selectors are used (example 12.3). Example 12.3. Using Child Selectors HTML5 CSS 2.1 IE Cr Op Sa Fx
In this example, child selectors are required to separate the style of the list items top level and nested lists that do different tasks, so the style for them should not overlap. 1. What color will the bold italic text be in the code? Illumination standards are based on based on the classification of visual work according to certain quantitative characteristics. When using the following style? P ( color: green; ) 2. Which element is the parent element for the tag 3. For which tag is the elementacts as a parent? 1. Olive. 3. Not for any tag. Tagis responsible for the document type in HTML (DTD "document type definition", description of the document type). To be more precise, these are instructions for the browser what type of document is presented below. Arises logical question: is html really different? The point is that in different html versions new tags appeared. New properties also appeared in CSS. In order for the browser to correctly understand which standard the page complies with, it is recommended to clearly indicate the document type in
. Locatedat the very beginning of the html code (before the tag
). Syntax
Let's look at which standard values are most common. To sum up, we can say thatis not mandatory element, but its use reduces the risk of problems with displaying the html page in different browsers. In fact, the following option will suit everyone: Today let's get started learning html and css. I will try to explain this topic as clearly as possible for any reader. And it doesn’t matter whether you are familiar with this topic or just have a desire to study the code, which is quite widely used in website building. And to touch as much as possible more examples application and use of code, I plan to write a very impressive list of articles dedicated to, without using any cms, or combining html pages with the dle and wordpress engines. We will analyze questions as they arise, and not in the traditional style, first theory, and then practice. I will immediately show everything in practice, supporting everything with theory. But let's start, of course, from the beginning. That is, what is html? And another important question: “Why do you need a doctype and which one to choose?” Actually, this is the topic of today’s post. Html is an abbreviation for HyperText Markup Language, which defines the arrangement of elements on a web page and their design. This language does not limit the webmaster in any way in his imagination and allows him to create almost any structure and design of the page. In general, if you decide to devote yourself to creating websites, you must know html code. There is nothing complicated about it, and I hope that based on the results of the series of articles, you will be convinced of this. Any website code begins with a document type definition (DTD - document type definition (document type description)) by browsers in order to correctly display the site on our monitors. And to help the browser decide, you need to indicate the type of document that is used on the site. There is a tag for this Now, let's try to figure out piece by piece what DOCTYPE contains. PUBLIC - determines the public nature of the document. This type document is public. “-” indicates whether the document type developer is registered or not with the International Organization for Standardization (ISO). It has two meanings: minus or plus. Minus: not registered. Plus - registered. But for W3C, “-” is indicated W3C is the organization that developed DTD. DTD - document type. For HTML and XHTML, a DTD is specified. HTML 4.01 Transitional (as an example) - the name of the document, its version and the syntax it uses. EN is the language in which the document is written. And of course, HTML and XHTML use English. http://www.w3.org/TR/html4/loose.dtd - address of the document description document (DTD). That's how much information the very first one carries. HTML string or XHTML code. But problems may still arise in determining whether our document matches the chosen syntax or not. For this, there is a markup validator that will help us determine how valid (correct) our code is. The validator is provided by the same organization. which is the official developer of DTD. It is located on the website http://validator.w3.org/. So, we just have to make a choice. And choose That's all for me. I hope this post will be useful and help you understand the issue about DOCTYPE. Complex and heavy web applications have become common these days. Cross-browser and easy-to-use libraries like jQuery with their rich functionality can greatly help in manipulating the DOM on the fly. Therefore, it is not surprising that many developers use such libraries more often than working with the native DOM API, with which there were many problems. While browser differences are still an issue, the DOM is now in in better shape than 5-6 years ago when jQuery was gaining popularity. In this article, I'll demonstrate the HTML manipulation capabilities of the DOM, focusing on parent, child, and neighbor relationships. In conclusion, I will give information about browser support for these features, but keep in mind that a library like jQuery is still a good option due to the presence of bugs and inconsistencies in the implementation of native functionality. For demonstration I will use the following HTML markup, we will change it several times throughout the article: 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, it returns a collection HTML elements, located inside the requested element; to count their number I use length property this collection. In the second example, I'm using the childElementCount method, which I think is a neater and potentially more maintainable way (discuss this more later, I don't think you'll have trouble understanding what it does). I could try using 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. To check if an element has child nodes, I can use the hasChildNodes() method. The method returns a Boolean value 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 aren't any; The markup now 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 takes into account 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 whitespace, I'll first check for the existence of child nodes, then use the nodeType property to determine if there are any element nodes among them. There are techniques you can use to add and remove elements from the DOM. The most famous of them is based on a combination of the createElement() and appendChild() methods. Var myEl = document.createElement("div"); document.body.appendChild(myEl); IN in this case I'm creating But instead of inserting specifically element being created, I can also use appendChild() and just move the existing element. Let's say we have the following markup: 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 Notice 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 using removeChild() . Here's how to delete our list 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 so I can save it in case I need it later. Var myOldChild = document.body.removeChild(myList); document.body.appendChild(myOldChild); There is also a ChildNode.remove() method that was relatively recently added to the specification: Var myList = document.getElementById("myList"); myList.remove(); This method does not return the remote object and does not work in IE (Edge only). And both methods remove text nodes in the same way as element nodes. I can replace an existing child element with a new one, regardless of whether this one exists new element 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); As you can see, the replaceChild() method takes two arguments: the new element and the element it replaces. old element. I can also use this method to move an existing element. Take a look at next HTML: Example text 1 Example text 2 Example text 3 I can replace the third paragraph with the first paragraph using 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 There are several different ways selecting a specific 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 their names suggest they do: select the first and last child elements. Let's return to our markup: 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 one. 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. In general, properties that consider only element nodes are more useful than those that select all nodes. 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 is a simple insertBefore() method, much like replaceChild(), it takes two arguments and works with both new elements and existing ones. Here's the markup: Example Paragraph Notice the paragraph I'm going to remove 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 appear before the list and this is another way to wrap the element. Example Paragraph Like replaceChild(), insertBefore() takes two arguments: the element to be added and the element before which we want to insert it. This method is simple. Let's try more now powerful way inserts: insertAdjacentHTML() method.
Questions to check
B (color: blue; )
I (color: orange; )
B > I ( color: olive; )
P > I ( color: yellow; )
Answers
Top level element] [Publicity ] "[Registration ]//[Organization ]//[Type ] [Name ]//[Language ]" "">
...
Table with valuesand descriptions for them
DOCTYPE
Description
Strict HTML syntax
Transitional HTML syntax
HTML document uses frames
HTML5 standard. For all documents. It is recommended to use it on your websites.
Strict XHTML syntax. Includes all HTML elements and attributes, except legacy presentation ones. Framesets are also not allowed.
Transitional XHTML syntax. Includes all HTML elements and attributes, along with legacy presentation ones. Framesets are not allowed.
Same as XHTML 1.0 Transitional, but allows frames.
Same as XHTML 1.0 Strict, but allows adding modules.
Whichchoose
...
What is html?
DOCTYPE
Description
HTML 4.01
Strict HTML syntax.
Transitional HTML syntax.
HTML document using frames.
HTML 5
For all documents.
XHTML 1.0
Strict XHTML syntax.
Transitional XHTML syntax.
XHTML document using frames.
XHTML 1.1
Same as strict XHTML syntax, but adding modules is allowed.
html - indicates the top-level element, that is, the very basis of the code. For HTML, this is a tag .Counting child nodes
Checking the existence of child nodes
Adding and Removing Children Elements
Replacing child elements
Selecting specific children
Inserting content into the DOM