An article on DOM

Keywords: Javascript Attribute xml

Learning JavaScript is bound to encounter DOM operations, so what is DOM? What is it for? This article gives you the answer.

DOM is the abbreviation of document object model, referred to as document object model.

Simply put, DOM is a set of abstraction and conceptualization methods for the content of documents. We can model HTML documents and treat them as objects.

Basic concepts:

Document: HTML or XML file.

Node: Everything in an HTML document can be called a node. Common nodes are element nodes, attribute nodes, text nodes and annotation nodes.

Element: Tags in HTML documents can be called elements.

We can think of an HTML document as a tree-structured object, with each tag forming a branch, which is easy to understand, as shown in the following figure (pictures from w3school).

 

Knowing what DOM is, I must ask what DOM is useful for.

DOM abstracts HTML documents into an object, which must be for the convenience of using JavaScript to manipulate HTML documents. The function of DOM is to manipulate the structure and content of the page and increase the dynamic characteristics of the page.

Okay, now that we know what DOM is for, let's learn how to do it.

DOM operations are mainly divided into four parts:

1. Getting HTML nodes and modifying their properties

2. Modifying Node Styles

3. Binding events to nodes

4. Node operation

Now let's make an introduction.

Get HTML nodes and modify node properties (including form elements)

DOM provides three ways to get nodes

Method 1:

getElementById ()// Gets a DOM object based on id attribute, case-sensitive, code-compliant

Finding an element by ID (an element object is found) can only be invoked by a document object (id cannot be repeated in the same document).

<div id="box"></div>

var box = document.getElementById("box");

 

Method two:

getElementsByTagName ()// / Returns multiple DOM objects based on the tag

Finding a class of elements by tag name (a pseudo array consisting of element objects found) can be called by document or element object. When called by element object, it means that the search is performed inside the element object.

Usually for multiple tags, and a for loop is often used.

<div class="cl" id="cl">

    <div class="cl2"></div>

    <div class="cl2"></div>

</div>

<div class="cl"></div>

<div class="cl"></div>


var divs = document.getElementsByTagName("div");// Get all on the page div,divs Is a pseudoarray

var cl = document.getElementById("cl");// Obtain id by cl Elements

var cl2s = cl.getElementsByTagName("div");// Obtain cl All of the following elements div Label,cl2s Is a pseudoarray

Method three:

getElementsByClassName()

Find a class of elements by class name.

<div class="cl" id="cl">

    <p class="cl"></div>

    <span class="cl"></div>

</div>

<a class="cl"></a>

var cls = document.getElementsByClassName("cl");//What you get is a pseudo array,It's filled with div p span a These four element objects

 

Once we get the node elements, we can modify the attributes of the node elements.

DOM also provides two methods for us to obtain and modify attribute values of elements.

getAttribute()

getAttribute is a function that retrieves node attributes. It has only one parameter, that is, the name of the attribute to be queried. getAttribute does not belong to the document object, all can not be called through the document object, only through the element node object.

<div id="box" title=hello></div>
var box = document.getElementById("box"); console.log(box.getAttribute("title"));

In this way, we can get the title attribute value of the element box as hello.

setAttribute()

setAttribute is also a function for modifying node properties. Similar to getAttribute usage, the difference is that it has two parameters, the first is the attribute name and the second is the set attribute value.

<div id="box" title=hello></div>


var box = document.getElementById("box");

console.log(box.setAttribute("title","world"));

At this point, the title attribute value of the box node has changed to world.

Does it feel so easy?

In fact, there is a more convenient way to modify the attribute value, just use point grammar.

Get attribute values

var variable = box.title;

Modify attribute values

box. Attribute name = "attribute value";

Does it feel simpler?

Here I only give an example of the title attribute. Of course, there are many attributes of the element, such as the src attribute of the img tag. We can change the src attribute to switch pictures. You can also set the properties of form elements

Type can set the type of input element.

Value can set the value of input element.

checked can set whether the input element is selected or not.

Select: You can set whether the option in the drop-down list select is selected or not.

Disabled can set whether the input element is disabled.

All right, that's the end of the property operation.

Getting Nodes and Control Styles

There are only three methods for node acquisition, but the actual project HTML documents are often very complex.

All nodes in the document have this or that relationship. The relationships between nodes can be described by traditional family relationships, which is equivalent to the analogy of document tree to genealogy. In HTML, the < body > element can be regarded as a child of the < HTML > element; accordingly, the < HTML > element can be regarded as the parent of the < body > element. The < head > elements can be regarded as sibling elements of < body > elements, because they are the direct children of the same parent element < HTML >.

First, let's look at the hierarchical structure of documents, and what are the relationships between them.

childNodes // child node

children // child elements are not a method in the early DOM standards, but all browsers support them.

 

Next Sibling// Next Brother Node

nextElementSibling// Next sibling element compatibility problem

Previous Sibling// Last Brother Node

Previous Element Sibling// Compatibility of the previous sibling element

 

First Child // First Node

First ElementChild // First Subelement Compatibility Problem

lastChild // Last child node

Last ElementChild // Last Subelement Compatibility Problem

 

parentNode // parent node (must be element node, so no processing is required)

There is no compatibility problem for all acquired node-related attributes

Note: Nodes and elements are not the same concept, as we said at the beginning of this article, so let me remind you.

Getting child nodes & child elements

  • childNodes: Gets the child nodes of the specified element, including text nodes, element nodes, etc.
  • children: Get the child elements that know the element, only the element nodes. <ul id="list">
    <li><a href="javascript:void(0)">home page</a></li>

    <li><a href="javascript:void(0)">Podcast</a></li>

    <li><a href="javascript:void(0)">Blog</a></li>

    <li><a href="javascript:void(0)">Album</a></li>

    <li><a href="javascript:void(0)">about</a></li>

    <li><a href="javascript:void(0)">Help</a></li>

</ul>
<script> var ul = document.getElementById("list"); var lis = ul.getElementsByTagName("li"); //Do not care about the hierarchy, only find the specified label //Disadvantage: If there is one inside li Also will find var nodes = ul.childNodes; //Sub-nodes only find sub-levels //Disadvantage: In addition to the element nodes we want, we also get other nodes. var children = ul.children;//Subelement

</script>

childNodes is the method specified in the DOM standard. The way to get nodes is supported by all browsers.
children is not a method specified in the DOM standard because it is very common for all browsers to support it.

In practical application, children are basically used.

Get the next sibling node

Next Sibling: Next Brother Node

<input type="text" id="txtName">

<span></span>

<input type="text" id="txtPwd"><span></span>

<input type="button" id="btn" value="register">

 <script>

var txt = document.getElementById("txtName");

var next = txt.nextSibling;// What you get is a newline,Empty text node

var pwd = document.getElementById("txtPwd");

var next = pwd.nextSibling;// What you get is span element,Because there are no other nodes between the two tags

 </script>

Get the next sibling element

Next Element Sibling: The Next Brother Element

<input type="text" id="txtName">

<span></span>

 <script>

var txt = document.getElementById("txtName");

var next = txt.nextElementSibling;// Available span element,Get only the next sibling element,Nodes that ignore non-element types

 </script>

Get the parent node

parentNode: Gets the parent node of the element, which must be an element

<div id = "box">
    <img src="1.jpg" id="img"/>
</div>
<script>
var img = document.getElementById("img");
var parent = img.parentNode; //What you get is id by box Of div element
 </script>

I'll start with the acquisition of nodes, and I'll add a few more questions about compatibility.

Let's look at how to style a node.

Get style

  • Only in-line styles can be retrieved through style
  • If there are units in the acquired style, the acquired style will also have units in it. The type is a string.

Set style

1. Styling through style

  • Inside-line styles set through style
  • If the style requires units, you need to bring them with you when setting them up.
div{

    width:100px;

    height:100px;

}

<div id="box"></div>

var box = document.getElementById("box");

consloe.log(box.style.width);// It prints empty strings because only in-line styles can be obtained.

box.style.width = "300px";// Set the in-line style,And you have to bring units here.

console.log(box.style.width);// The print is "300" px"/

 

2. Setting Styles by Class Name

.b{

    width:100px;

    height:100px;

    background-color:red;

}

<div id="box"></div>

var box = document.getElementById("box");

// There are two ways to set style by class name

box.className = "b";

box.setAttribute("class","b");

Here's an introduction to event binding

Binding events

Event Three Elements: Event Source Event Handler

Event source.Event = function(){

    // Event Handler

}

<img src="pic.jpg" id="img"/>

var img = document.getElementById("img");

img.onclick = function(){

   ...

}

img is the event source event, clicking onclick event handler is the content in the body of the function

Here is a summary of common events

attribute

describe

Onblur

Elements lose focus.

Onchange

The content of the domain is changed.

Onclick

The event handle that is invoked when the user clicks on an object.

ondblclick

The event handle that is called when the user double-clicks an object.

Onfocus

Elements get focus.

onkeydown

A keyboard key is pressed.

onkeypress

A keyboard key is pressed and released.

Onkeyup

A keyboard key is released.

Onload

A page or an image is loaded.

onmousedown

The mouse button is pressed.

onmousemove

The mouse is moved.

onmouseout

Mouse moves away from an element.

onmouseover

Mouse over an element.

onmouseup

The mouse button is released.

Onreset

The reset button is clicked.

Onresize

The window or frame is resized.

Onunload

The user exits the page.

 

Node operation

There are five forms of node operation: cloning nodes, adding nodes, inserting nodes, removing nodes and creating nodes.

Clone Node ()

element.cloneNode(): Replicate element nodes

Parameter: Boolean value,

true represents deep cloning, replicating the current node and all internal nodes

false represents shallow cloning, replicating only the current node

<div id="father">

    <div id="son"><div/>

</div>

var father = document.getElementById("father");

var son = document.getElementById("son");

var clone = son.cloneNode(true);// hold son this div Reproduced clone and son It doesn't matter.

Add node - appendChild()

father.appendChild(son): Append the son node to the last position inside the father

<div id="father">
    <div id="son"><div/>
</div>
<div id="demo"></div>

var father = document.getElementById("father");
var demo = document.getElementById("demo");
var clone = demo.cloneNode(true);// take demo Clone a copy

father.appendChild(clone);// Cloned clone Append to father in

// At this point, the page structure should be

<div id="father">

    <div id="son"><div/>

    <div id="demo"></div>

</div>

<div id="demo"></div>

//Additional cloned nodes will not affect the original node.

//If the code is as follows, the demo node is moved directly to the father node

father.appendChild(demo);// demo is the node that exists on the page

//At this point, the page structure should be

<div id="father">

    <div id="son"><div/>

    <div id="demo"></div>

</div>

 

Insert node - insertBefore()

father.inserBefore(son1,son2): Insert son1 in front of son2 under the father node

<div id="father">

    <div id="son"><div/>

</div>

<div id="demo"></div>

var father = document.getElementById("father");

var son = document.getElementById("son");

var demo = document.getElementById("demo");

father.inserBefore(son,demo);//Will directly demo Nodes move to father Lower son Front       

Inserting cloned nodes will not affect the original node.

 

Remove node - removeChild()

father.removeChild(son): Remove the son node under father

<div id="father">

    <div id="son"><div/>

</div>

var father = document.getElementById("father");

var son = document.getElementById("son");

father.removeChild(son);// Direct will son Node deletion

Create node

document.write()

Feature: It can only be called by document, and it will cover the original content on the page.

Document.write ("<a href=" http://www.baidu.com">Baidu</a>")

// You can create a label a on the page, and it will cover all the content on the page.

innerHtml()

Features: Adding html tags to pages can limit the scope

<div id="box"></div>

var box = document.getElementById("box");

box.innerHtml = "<a href="http://www.baidu.com">Baidu</a>";

// The additional structure is

<div id="box">

    <a href="http://Www.baidu.com">Baidu</a>

</div>

createElement()

Features: Create tags dynamically and add them to the page with appendChild.

<div id="box"></div>

var box = document.getElementById("box");
var input = document.createElement("input");

input.type = "text";
box.appendChild(input);

 

This is the end of the basic operation of DOM. If it helps you, please give this article a compliment O(_____)

Posted by chefou on Sun, 26 May 2019 12:35:22 -0700