jsDOM

1. DOM concept

  • The D in DOM stands for document.

If you don’t have a document, DOM doesn’t exist. When you create a web page that loads in the browser, the DOM is born behind the scenes. Your web page document is a document object, the D in the DOM.

  • The O in DOM stands for object.

We learned about objects in the last chapter, including user-created objects, built-in objects, and host objects, so the O stands for host objects, which is the part of the object provided by the browser.

  • The M in DOM stands for “model.”

The first thing to know here is what does a literal model mean? In our daily life, our common models mainly include airplane models, car models, human models and so on. No matter what the models are, they are the manifestations of some things. Just as a model plane represents a real plane, a city map represents a city. So, here’s model is refers to our web page, all HTML elements in this web page is a component of the model, they contain each other and coordinate each other, form a relation of father and son, brothers, are similar to each branch of a tree, up the many branches of a tree, the tree is a model.

Node 2.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Concept of node</title>
</head>
<body>
 	<h1>This is a headline</h1>
    <p title="The description of this passage.">It's a text description, it's a paragraph</p>
    <p>The test data</p>
    <ul id="purchases">
        <li class="sale">Here's a list</li>
        <li class="sale">Here's a list</li>
        <li class="sale">Here's a list</li>
        <li class="sale">Here's a list</li>
    </ul>
</body>
</html>
Copy the code

2.1 Concepts of nodes

Let’s take the structure of a web page. After the DOCTYPE, an HTML tag marks the beginning of the entire document, and all other elements of the web page are contained in this tag. Then, in accordance with the father-son and brotherly relationship we just said, the HTML tag is at least a father, because all the elements and other elements are contained in its internal, he has neither father nor brother, if you really want to say where it comes from, then, we will compare it to nuwa. Further down we find the two branches, and they are on the same level and do not contain each other, so they are brothers, equals. Their fathers are HTML tags. Go down deep, and so on, can use father and son, brother relationship to describe such a page, constitute these father and son brothers of the elements of the separation point, we call it a node.

2.2 Node Classification

  • Element nodes

Take this web page as an example, its element nodes are the HTML tags that constitute the structure of the web page, specifically to this web page is <\h1>, <\p>, <\ul> these elements are called element nodes.

  • Text node

In a web page, most of the content is provided by text. For example, the text contained in the P tag in this web page is a text node. Generally, text nodes in a web page are always contained inside element nodes, but not all element nodes contain text nodes.

  • An attribute node

An attribute node is a more specific description of an element node, such as its type, description, etc. For example, most elements have a title attribute, which is used to explain the content of each element. This node is an attribute node.

3. Get the element

3.1 Methods for obtaining elements

  1. Obtained by the ID attribute of the element node
document.getElementById(id)
Copy the code
  1. Retrieved by element, it returns an array of objects
var Uli = document.getElementsByTagName(li)
var count = Uli.length
console.log(count)
> 4
for(var i=0; i<count; i++){
    // Pop Object four times and return an array of objects
    alert(typeof Uli[i])
}
Copy the code
  1. Use both together

If we give ul an attribute with an ID that is damaged, let’s get how many list items the ID attribute value contains.

var shopping = document.getElementById("purchases")
var items = shopping.getElementsByTagName("*")
console.log(items.length)
Copy the code
  1. Obtained by the class attribute of the element
/ / grammar
document.getElementsByClassName("class")
Copy the code

Note: This method returns a value similar to getElementsByTagName(), which returns an element array object with the same class name. Notice that the word Elements in the middle has an s at the end, and notice the difference from getElementById().

  1. Get the element through a CSS selector
// Retrieve the elements in the document whose id=" damaged ":
document.querySelector('#purchases')

// Get the first P element in the document
document.querySelector("p")

// Get the first P element in the document with class="sale"
document.querySelector("p.sale")

// Get the first p element in the document with the title attribute
document.querySelector("p[title]")
/** The following example demonstrates the use of multiple selectors. Suppose you select two selectors: 

and

elements. The following code adds a background color to the first

element of the document: **/

document.querySelector("h2, h3").style.backgroundColor = "red"; Copy the code
  • QuerySelectorAll () gets all the elements and returns an array object
var lisale = document.querySelectorAll("li.sale")
for(var i=0; i<lisale.length; i++){
    lisale[i].style.color = "red"
}
Copy the code

3.2 Summary of Knowledge points

  • A document is a tree of nodes
  • There are different types of nodes: element nodes, attribute nodes, and text nodes
  • GetElementById () returns an object that corresponds to a specific element node in the document
  • Both getElementsByTagName() and getElementsByClassName() return an array object, each corresponding to a specific set of element nodes.
  • Each node is an object
  • QuerySelector () can retrieve elements from CSS selectors, attribute selectors, and element tags, returning a specific element node, or returning the first of multiple elements.
  • QuerySelectorAll () returns an array object that corresponds to a specific set of element nodes

4. Get and set properties

Once we have an element, we can try to get its attributes and change the values of the attribute nodes accordingly.

4.1 getAttribute() Obtains an attribute

Grammar: access to the element object, through the object. The getAttribute () to obtain the object’s properties, she has only one parameter, are you going to query the name of the property.

Object.getAttribute(attribute)
Copy the code

Note: This method is not part of the document, so it cannot be called using the document object. It can only be called through the element node object.

// getAttribute() Gets the attribute
var Plist = document.getElementsByTagName('p')
for(var i=0; i<Plist.length; i++){
    // Use the conditional statement we have learned to execute only when there are properties
    if(Plist[i].getAttribute('title') != null){
        alert(Plist[i].getAttribute('title'))}; }Copy the code

Improving code, writing less is best:

var Plist = document.getElementsByTagName('p');
for(var i=0; i<Plist.length; i++){
	var title_text = Plist.getAttribute('title')
// If is written on a single line without braces, simply to check whether the value exists
	if(title_text) alert(title_text)
}
Copy the code

4.2 setAttribute() Modifies the attribute value of an element node

The setAttribute() method is used to modify the value of an element node attribute. Like getAttribute(), it can only be used on element nodes.

Object.setAttribute("Animal name"."Value")
Copy the code

Note: This method takes two arguments. The first argument is the name of the property to be modified and the second is the value to be modified.

Modify attributes synthesis case exercise:

// setAttribute() modifies the attribute value
var Plist = document.getElementsByTagName('p')
for(var i=0; i<Plist.length; i++){
    // Use the conditional statement we have learned to execute only when there are properties
    if(Plist[i].getAttribute('title')) {console.log(Plist[i].getAttribute('title'))
        Plist[i].setAttribute("title"."Here's my modified value.")
        console.log(Plist[i].getAttribute("title"))}; } > Description of this text > Here is my modified valueCopy the code

SetAttribute () can also add attributes directly to an element and assign values to it

var Plist = document.getElementsByTagName('p')
for(var i=0; i<Plist.length; i++){
    var title_text = Plist[i].getAttribute('title');
    if(title_text){
        // Return the title attribute directly
        console.log(title_text);
    }else{
        // If it does not exist, add it and print the result
        Plist[i].setAttribute('title'."I added another blank.");
        new_title_text = Plist[i].getAttribute('title');
        console.log(new_title_text); }; }; > Description of this text > I added another blankCopy the code

5.DOM Knowledge summary

This chapter focuses on the five methods provided by DOM

  • GetElementById () returns a specific element node object
  • getElementsByTagName()
  • GetElementsByClassName () these two return a specific set of array objects
  • GetAttribute () gets the attribute value
  • SetAttribute () modifies the attribute value and sets the attribute and value
  • QuerySelector () can retrieve elements from CSS selectors, elements, and attributes, returning the first of many
  • QuerySelectorAll () returns a specific set of array objects