Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of ECMAScript, BOM and DOM in JavaScript

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you the JavaScript ECMAScript, BOM, DOM example analysis, I believe that most people do not know much, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

A brief introduction to JavaScript

JavaScript is a scripting language that interprets and executes. It is a dynamically typed, weakly typed, prototype-based language with built-in support for typing. It follows the ECMAScript standard. Its interpreter, known as the JavaScript engine, is part of the browser and is widely used in client-side scripting languages, mainly to add dynamic functionality to HTML.

Almost all major languages can be compiled into JavaScript, which can be executed in browsers on all platforms, which also reflects the strength of JavaScript and its importance in Web development. Such as Blade: a Visual Studio extension that converts C # code into JavaScript,Ceylon: a modular, statically typed JVM language that can be compiled into JavaScript.

JavaScript is a language that can run in both front and background. For example, Node.js is a JavaScript runtime environment based on the Chrome V8 engine (similar to Java or .NET). Node.js uses an event-driven, non-blocking Istroke O model to make it lightweight and efficient.

1.1.The composition of javascript

ECMAScript, which describes the syntax and basic objects of the language, such as types, operations, process control, object-oriented, exceptions, etc.

Document object Model (DOM), which describes the methods and interfaces for dealing with web page content.

Browser object Model (BOM), which describes the methods and interfaces for interacting with browsers.

JavaScript consists of objects, and everything is an object.

1.2. features of JavaScript scripting language

A), interpretive scripting language. JavaScript is an interpreted scripting language. Languages such as C and C++ are compiled and then executed, while JavaScript is explained line by line in the process of running the program.

Based on object. JavaScript is an object-based scripting language that can not only create objects, but also use existing objects.

B), simple. The JavaScript language uses weak variable types and does not make strict requirements on the data types used. It is a scripting language based on Java basic statements and control, and its design is simple and compact.

C), dynamic. JavaScript is an event-driven scripting language that responds to user input without going through a Web server. When visiting a web page, JavaScript can directly respond to these events when the mouse clicks or moves up and down, window movement and other operations in the web page.

D), cross-platform. The JavaScript scripting language does not depend on the operating system and only needs the support of browsers. Therefore, a JavaScript script can be written and used on any machine, on the premise that the browser on the machine supports the JavaScript scripting language, and JavaScript is currently supported by most browsers.

II. ECMAScript (JavaScript Core and Grammar) 2.1.Definitions of ECMAScript

1) ECMAScript is a standard (European Association of computer Manufacturers), JavaScript is only one implementation of it, other implementations include ActionScript (Flash script)

2) ECMAScript can provide core scripting capabilities for different kinds of hosting environments, that is, ECMAScript is not bound to the specific hosting environment, for example, the hosting environment of JavaScript is the browser, and the hosting environment of AS is Flash. 、

3) ECMAScript describes the following: syntax, type, statement, keyword, reserved word, operator, object, etc.

2.2, data type

In JS, you use the var keyword to declare a variable, and the type of the variable is determined according to its assigned value (dynamic type). The data types in JS are divided into original data types (5) and reference data types (Object types).

1) five raw data types: Undefined, Null, Boolean, Number and String. It is important to note that strings in JS are of the original data type.

2) typeof operator: check the variable type. Calling the typeof operator on a variable or value returns one of the following values:

Undefined-if the variable is of type Undefined

Boolean-if the variable is of type Boolean

Number-if the variable is of type Number

String-if the variable is of type String

Object-if the variable is of a reference type or Null type

3) solve the problem of reference type judgment by instanceof operator

4) null is considered a placeholder for an object, and the typeof operator returns "object" for null values.

5) the original data type and reference data type variables are stored in memory as follows:

6) definition of types in JS: a collection of values. For example, there are two values of type Boolean: true and false. Both the Undefined and Null types have only one value, undefined and null, respectively.

The Null type has only one value, which is null, and the Undefined type has only one value, undefined. Both null and undefined can be used directly in JavaScript code as literals (literal).

Null is related to an object reference and is represented as an empty or non-existent object reference. When a variable is declared without a value assigned to it, its value is undefined.

The value of undefined appears in the following situations:

Gets a property from an object whose value is undefined if none of the objects in the object and its prototype chain have the property.

If a function does not explicitly return a value to its caller through return, its return value is undefined. One special case is when using new.

Function in JavaScript can declare any formal parameter. When the function is actually called, if the number of passed parameters is less than the declared formal parameter, then the value of the extra formal parameter is undefined.

Example:

/ / js object var user = {name: "Jacky Cheung", address: "Hong Kong, China"}; console.log (user.age); / / property in the access object, var I is not defined; console.log (I); / / variable is not assigned function f (N1) {console.log (N1);} var result=f (); / / parameter is not assigned console.log (result); / / undefined if the function does not return a value

Results:

There are some interesting features about null and undefined:

If you use the typeof operator on a variable with a value of null, the result is object

Use typeof for the value of undefined, and the result is undefined.

For example, typeof null = = "object" / / true; typeof undefined = "undefined" / / true null = = undefined / / true, but null! = = undefined / / true

Example:

/ / js object var user = {name: "Jacky Cheung", address: "Hong Kong, China"}; console.log (typeof (user)); console.log (typeof (null)); console.log (typeof (undefined)); console.log (user.name); console.log (user.age); if (user.age) {console.log (user.age);} else {console.log ("No age attribute");} / for false case var I Console.log (!! "); console.log (! 0); console.log (! + 0); console.log (!-0); console.log (! NaN); console.log (!! null); console.log (!! undefined); console.log (typeof (I)); console.log (!! I); console.log (false); / / whether it is not a number, is Not a Number console.log (isNaN (" Five ")); console.log (isNaN (" 5 "))

Results:

7), the particularity of boolean type

8), = and =

There are two operators in JavaScript to determine whether the values are equal, = = and = =. Compared with the two, = = does some type conversion, while = = does not do type conversion and accepts more stringent conditions of equality.

Comparison types are compared when comparing

Of course, it corresponds to! = and! =

Try to use = instead of =

Console.log ("5" = = 5); / / trueconsole.log ("5" = 5); / / falseconsole.log ("5"! = 5); / / falseconsole.log ("5"! = = 5); / / true2.3, local and global variables

Variables declared in a function can only be used in a function. When you exit the function, the variable is released. This variable is called a local variable. Because each local variable is only valid in its own function, you can use a variable with the same name in different functions.

If you declare a variable outside a function, it can be used by all functions on the page. After the global variables are declared, they take effect. The variable will not be invalidated until the page is closed.

Note: in the JS language, variables declared in the code block are global variables.

JavaScript is a language that is not strict with data type variables, so it is not necessary to declare the type of every variable. Although variable declaration is not necessary, it is a good habit to declare variables before using them. You can use the var statement to declare variables. For example, the value stored in var men = true; / / men is of type Boolean.

Variable naming

JavaScript is a case-sensitive language, so naming a variable best is different from naming it Best.

In addition, the length of the variable name is arbitrary, but the following rules must be followed:

1. The first character must be a letter (uppercase and lowercase), or an underscore (_) or a dollar sign ($).

two。 Subsequent characters can be letters, numbers, underscores, or dollar signs.

3. Variable name cannot be a reserved word.

You can define variables without using var, but the variables so defined are global variables.

Example:

Function a () {var N1: 1; N2: 2; / / declares N2 without var, so N2 is a global variable, try to avoid console.log (N1 + "," + N2);} a (); console.log (N2); console.log (window.n2); console.log (window.n1); console.log (N1).

Results:

2.4.Array (Array)

In ① js, array element types can be inconsistent.

In ② js, the array length can be changed dynamically.

③ follows the above code, and typeof arr and arr instanceof Array output object and true, respectively.

Console.log (typeof (names)); / / objectconsole.log (names instanceof Array); / / trueconsole.log ("" instanceof String); / / false is not an object type console.log (true instanceof Boolean); / / false

Array objects and methods

Array's internal support for arrays

Array.concat () join array

Array.join () concatenates array elements to build a string

Size of the Array.length array

Array.pop () deletes and returns the last element of the array

Array.push () adds elements to the array

Array.reverse () reverses the order of the elements in the array

Array.shift () moves the element out of the array

Array.slice () returns part of the array

Array.sort () sorts array elements

Array.splice () inserts, deletes, or replaces elements of an array

Array.toLocaleString () converts an array to a local string

Array.toString () converts the array to a string

Array.unshift () inserts an element into the array header

2.4.1. Create var arrayObj = new Array (); var arrayObj = new Array ([size]); var arrayObj = new Array ([element0 [, element1 [,... [, elementN])

Example:

Var array11 = new Array (); / / empty array var array12 = new Array (5); / / specified length, but cross-boundary var array13 = new Array ("a", "b", "c", 1, "a", "b", "c", 1); / / define and assign var array14= []; / / empty array, grammatical sugar var array15= [1MJ 2, "x", "y"]; / define and assign 2.4.2, access and modify

Var testGetArrValue=arrayObj [1]

ArrayObj [1] = "value"

Array12 [8] = "hello array12"; / / assign or modify console.log (array12 [8]); / / take a value / / traverse for (var I = 0; I

< array13.length; i++) { console.log("arrayl3["+i+"]="+array13[i]);}//枚举for(var i in array15){ console.log(i+"="+array15[i]); //此处的i是下标} 结果: 2.4.3、添加元素 将一个或多个新元素添加到数组未尾,并返回数组新长度 arrayObj. push([item1 [item2 [. . . [itemN ]]]]); 将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度 arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]); 将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回被删除元素数组,deleteCount要删除的元素个数 arrayObj.splice(insertPos,deleteCount,[item1[, item2[, . . . [,itemN]]]]) 示例代码: //4.3、添加元素 var array31=[5,8]; //添加到末尾 array31.push(9); var len=array31.push(10,11); console.log("长度为:"+len+"--"+array31); //添加到开始 array31.unshift(4); var len=array31.unshift(1,2,3); console.log("长度为:"+len+"--"+array31); //添加到中间 var len=array31.splice(5,1,6,7); //从第5位开始插入,删除第5位后的1个元素,返回被删除元素 console.log("被删除:"+len+"--"+array31); 运行结果: 2.4.4、删除 移除最后一个元素并返回该元素值 arrayObj.pop(); 移除最前一个元素并返回该元素值,数组中元素自动前移 arrayObj.shift(); 删除从指定位置deletePos开始的指定数量deleteCount的元素,数组形式返回所移除的元素 arrayObj.splice(deletePos,deleteCount); 示例: //4.4、删除 var array41=[1,2,3,4,5,6,7,8]; console.log("array41:"+array41); //删除最后一个元素,并返回 var e=array41.pop(); console.log("被删除:"+e+"--"+array41); //删除首部元素,并返回 var e=array41.shift(); console.log("被删除:"+e+"--"+array41); //删除指定位置与个数 var e=array41.splice(1,4); //从索引1开始删除4个 console.log("被删除:"+e+"--"+array41); 结果: 2.4.5、截取和合并 以数组的形式返回数组的一部分,注意不包括 end 对应的元素,如果省略 end 将复制 start 之后的所有元素 arrayObj.slice(start, [end]); 将多个数组(也可以是字符串,或者是数组和字符串的混合)连接为一个数组,返回连接好的新的数组 arrayObj.concat([item1[, item2[, . . . [,itemN]]]]); 示例: //4.5、截取和合并 var array51=[1,2,3,4,5,6]; var array52=[7,8,9,0,"a","b","c"]; //截取,切片 var array53=array51.slice(2); //从第3个元素开始截取到最后 console.log("被截取:"+array53+"--"+array51); var array54=array51.slice(1,4); //从第3个元素开始截取到索引号为3的元素 console.log("被截取:"+array54+"--"+array51); //合并 var array55=array51.concat(array52,["d","e"],"f","g"); console.log("合并后:"+array55); 结果: 2.4.6、拷贝 返回数组的拷贝数组,注意是一个新的数组,不是指向 arrayObj.slice(0); 返回数组的拷贝数组,注意是一个新的数组,不是指向 arrayObj.concat(); 因为数组是引用数据类型,直接赋值并没有达到真正实现拷贝,地址引用,我们需要的是深拷贝。 2.4.7、排序 反转元素(最前的排到最后、最后的排到最前),返回数组地址 arrayObj.reverse(); 对数组元素排序,返回数组地址 arrayObj.sort(); arrayObj.sort(function(obj1,obj2){}); 示例: var array71=[4,5,6,1,2,3]; array71.sort(); console.log("排序后:"+array71); var array72=[{name:"tom",age:19},{name:"jack",age:20},{name:"lucy",age:18}]; array72.sort(function(user1,user2){ return user1.age>

.

This set of operators is for integers, so it is completely useless for Javascript, because within Javascript, all numbers are saved as double-precision floating-point numbers. If you use them, Javascript has to convert the operands to integers before performing operations, which slows down the speed. And "bitwise and operator" & the same as "logic and operator" & &, it is easy to be confused.

9), function statement

There are two ways to define a function in Javascript:

Function foo () {}

And

Var foo = function () {}

The two writing methods are completely equivalent. However, when parsing, the former method will be automatically promoted to the head of the code by the parser, so it violates the requirement that the function should be defined before it is used, so it is recommended to use the latter method when defining the function.

10), wrapper objects of basic data types

The basic data types of Javascript include strings, numbers, and Boolean values, all of which have corresponding wrapper objects String, Number, and Boolean. So, someone would define the relevant value as follows:

New String ("Hello World"); new Number (2000); new Boolean (false)

Writing like this is completely unnecessary and very difficult to understand, so it is recommended not to use it.

In addition, new Object and new Array are not recommended and can be replaced by {} and [].

11), new statement

Javascript is the first widely used language in the world to support Lambda functions, which is essentially a functional programming language of the same kind as Lisp. But in the current world, more than 90% of programmers use object-oriented programming. In order to get closer to the mainstream, Javascript made a compromise and adopted the concept of classes, allowing objects to be generated from classes.

The class is defined as follows:

Var Cat = function (name) {this.name = name; this.saying = 'meow';}

Then, regenerate into an object.

Var myCat = new Cat ('mimi')

This syntax of generating classes using functions and objects using new is actually very strange and counterintuitive at all. Moreover, when using, it is easy to forget to add new, it will become an execution function, and then inexplicably a few more global variables. Therefore, it is recommended that you do not create objects in this way, but instead use a workaround.

Douglas Crockford gives a function:

Object.beget = function (o) {var F = function (o) {}; F.prototype = o; return new F;}

When creating an object, you use this function to manipulate the prototype object:

Var Cat = {name:'', saying:'meow'}; var myCat = Object.beget (Cat)

After the object is generated, you can assign values to the relevant attributes yourself:

MyCat.name = 'mimi'

12), void

In most languages, void is a type that means no value. But in Javascript, void is an operator that takes an Operand and returns undefined.

Void 0; / / undefined

This command is useless and confusing, so it is recommended to avoid it.

III. Summary of BOM3.1 and BOM

BOM (Browser Object Model) is the browser object model, which mainly refers to some browser built-in objects such as window, location, navigator, screen, history and other objects, which are used to complete some specific API of the browser.

A model used to describe the hierarchical relationship between objects. The browser object model provides a content-independent object structure that can interact with browser windows. BOM consists of multiple objects, of which the Window object that represents the browser window is the top-level object of BOM, and the other objects are children of that object.

BOM is the abbreviation of browser object model, abbreviated as browser object model.

BOM provides objects that interact with browser windows independent of content

Since BOM is mainly used to manage the communication between windows, its core object is window.

BOM consists of a series of related objects, and each object provides many methods and properties

BOM lacks standards, and the standardization organization of JavaScript syntax is ECMA,DOM. The standardization organization is W3C.

BOM was originally part of the Netscape browser standard

BOM structure

You can see from the figure above that DOM is an attribute that belongs to BOM.

The window object is the top-level (core) object of BOM, through which all objects are extended, and can also be called children of window.

Because window is a top-level object, its child objects can be called without indicating the window object.

You can write it in either of the following ways:

[xss_clean] ("www.jb51.net"); window. [XSS _ clean] (www.jb51.net); 3.2. BOM map

The BOM part is mainly aimed at browser content, in which window objects and location are commonly used.

Window is a global object through which a lot of scripting settings about browsers are made.

Location is related to the content of the address bar, such as wanting to jump to a page or getting some content through URL.

There is a lot of browser-related content in navigator, and browser types are usually determined by this object.

Screen is often used to determine the height and width of the screen.

History accesses the browser's history, such as forward, background, and jump to a specified location.

3.3.The window object

Window object plays a dual role in browsers: it is not only a global global object specified by ECMAscript, but also an interface for javascript to access browser windows.

MoveBy () function moveTo () function resizeBy () function resizeTo () function scrollBy () function focus () function blur () function open () function opener attribute alert () function confirm () function defaultStatus attribute status attribute setTimeout () function clearTimeout () function setInterval () function clearInterval () function

1. Get the position of the window relative to the upper left corner of the screen

_ window.onresize = function () {var leftPos = (typeof window.screenLeft = = 'number')? Window.screenLeft: window.screenX; var topPos = (typeof window.screenLeft = = 'number')? Window.screenTop: window. ScreenY; [xss_clean] (leftPos+ "," + topPos); console.log (leftPos+ "," + topPos);}

It is important to note that in IE,opera, screenTop saves the distance of the visible area of the page from the left side of the screen, while in chrome,firefox,safari, screenTop/screenY saves the distance of the entire browser area from the left side of the screen. In other words, the two differ from the pixel height of a browser toolbar.

2. Move the window and resize it

Window.moveTo (0mem0) window.moveBy (20recover10) window.resizeTo (100100); window.resizeBy (100100)

Note that these methods are likely to be disabled in browsers.

3. Get the size of the viewport on the browser page

Var pageWith=document.documentElement.clientWidth | | document.body.clientWidth;var pageHeight=document.documentElement.clientHeight | | document.body.clientHeight

4. Navigate and open windows

Window.open () can either navigate to a specific URL or open a new browser window that takes four parameters, the url to load, the window target (which can be the keyword _ self,_parent,_top,_blank), a property string, and a Boolean value indicating whether the new page replaces the currently loaded page in the browser history. Usually only the first parameter needs to be passed. Note that pop-up windows are blocked in many browsers.

5. Timer

SetTimeout (code,millisec)

The setTimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.

Code required, the JavaScript code string to be executed after the function to be called. =

Millisec required the number of milliseconds to wait before executing the code.

ClearTimeout (object) clears the set setTimeout object

Example:

Clear var btnClear=document.getElementById ("btnClear"); / / disable button var timer1=setTimeout (function () {btnClear.setAttribute ("disabled", "disabled");}, 5000) after 5 seconds; btnClear.onclick=function () {clearTimeout (timer1); / / clear timer alert ("timer stopped working, cleared");} / / Recursive, function setTitle () {document.title+= "- >"; setTimeout (setTitle,500);} setTimeout (setTitle,500)

Results:

SetInterval (code,millisec [, "lang"])

The setInterval () method can call a function or evaluate an expression according to a specified period (in milliseconds)

Code is required, the function to call or the code string to execute.

Millisec is required, the interval between periodic execution or calls to code, in milliseconds.

ClearInterval (object) clears the set setInterval object

6. System dialog boxes, the appearance of these dialogs is determined by the operating system / browser settings, css does not work, so many times you may need to customize the dialog box

Alert (): with an OK button

Confirm (): with a confirm and cancel button

Prompt (): displays a text input field in addition to the OK and Cancel buttons

Example:

Clear var btnClear=document.getElementById ("btnClear"); / / disable button var timer1=setInterval (function () {btnClear.style.width= (parseInt (btnClear.style.width | 0) + 10) + "px";}, 500) every 5 seconds; btnClear.onclick=function () {clearInterval (timer1); / / clear timer alert ("timer stopped working, cleared");} function setTitle () {document.title+= "- >";} setInterval (setTitle,500)

Results:

6. Scroll series methods

Height / width of the actual content inside the scrollHeight and scrollWidth objects (excluding border)

The distance from the top / left of the swept part of scrollTop and scrollLeft to the top / left of the visual area

Events triggered by scrolling the onscroll event scrollbar

Page scrolling coordinates:

Var scrollTop = window.pageYoffset | | document.documentElement.scrollTop | | document.body.scrollTop | | 0

3.4.The document object

Please refer to the contents of the Dom section

Write () function

Writeln () function

Document.open () function

Document.close () function

3.5.The location object

The location object provides information about the document loaded by the current window, as well as some navigation functions. In fact, this is a very special object. Location is both a property of the window object and a property of the document object.

Location.hash # contents returns the hash in url, or an empty string if the content after # is not included

Location.host best.cnblogs.com:80 returns the server name and port number

Location.port 80 returns the port number

Location.hostname best.cnblogs.com returns the server name

Location.href http://best.cnblogs.com returns the full url of the currently loaded page

Location.pathname / index.html returns the directory and file name in url

The protocol used by location.protocol http to return the page

Location.search? q=javascript returns the query string in url

Change the browser location: location.href= http://www.baidu.com

If you use location.replace ('http://www.baidu.com'), does not generate a new record in the history, the user cannot go back to the previous page.

Location.reload (): resets the current page, either from the cache or from the server; if forced from the server, pass in the true parameter

Example:

Console.log (location.href); console.log (location.port); console.log (location.search); / / location.href=location.href; / / Refresh / / location.reload (true); / / Force load. Refresh from cache without true

Results:

3.6.The history object

The history object keeps the history of the user surfing the Internet, and uses go () to jump in the user's browsing history:

History.go (- 1) is equivalent to history.back () history.go (1) is equivalent to history.forward () history.go (1) / / forward two pages history.go ('jb51.net') 3.7, navigator object

This object represents a browser instance and has many properties, but not too many commonly used ones. As follows:

Navigator.userAgent: user agent string for browser monitoring,

Navigator.plugins: browser plug-in array for plug-in monitoring

Navigator.registerContentHandler registration handlers, such as providing online processors such as RSS readers.

Sample code:

Title [xss_clean] ("browser name"); [xss_clean] (navigator.appCodeName); [xss_clean] ("minor version Information"); [xss_clean] (navigator.appMinorVersion); [xss_clean] ("full browser name"); [xss_clean] (navigator.appName); [xss_clean] ("browser version"); [xss_clean] (navigator.appVersion) [xss_clean] ("browser compiled version"); [xss_clean] (navigator.buildID); [xss_clean] ("whether cookie is enabled"); [xss_clean] (navigator.cookieEnabled); [xss_clean] ("client computer CPU type"); [xss_clean] (navigator.cpuClass); [xss_clean] ("whether the browser is java enabled"); [xss_clean] (navigator.javaEnabled ()) [xss_clean] ("browser main language"); [xss_clean] (navigator.language); [xss_clean] ("Array of MIME types registered in the browser"); [xss_clean] (navigator.mimeTypes); [xss_clean] ("whether to connect to the network"); [xss_clean] (navigator.onLine); [xss_clean] ("client computer operating system or CPU"); [xss_clean] (navigator.oscpu) [xss_clean] ("system platform on which the browser resides"); [xss_clean] (navigator.platform); [xss_clean] ("plugin information array in browser"); [xss_clean] (navigator.plugins); [xss_clean] ("user preferences"); / / [xss_clean] (navigator.preference ()); [xss_clean] ("Product name"); [xss_clean] (navigator.product) [xss_clean] ("secondary information of the product"); [xss_clean] (navigator.productSub); [xss_clean] ("language of the operating system"); [xss_clean] (navigator.systemLanguage); [xss_clean] ("browser's user agent string"); [xss_clean] (navigator. UserAgent); [xss_clean] ("operating system default language"); [xss_clean] (navigator.userLanguage); [xss_clean] ("user's personal Information object"); [xss_clean] (navigator.userProfile); [xss_clean] ("browser Brand"); [xss_clean] (navigator.vendor); [xss_clean] ("browser vendor secondary information"); [xss_clean] (navigator.vendorSub)

Running result:

/ * browser name Mozilla minor version information undefined full browser name Netscape browser version 5.0 (Windows NT 6.1 WOW64) AppleWebKit/537.36 (KHTML Like Gecko) whether the compiled version of the Chrome/61.0.3163.100 Safari/537.36 browser undefined enables the cookietrue client computer CPU type undefined browser whether the javafalse browser main language MIME type array registered in the zh-CN browser [object MimeTypeArray] is connected to the network true client computer operating system or the system platform where the CPUundefined browser is located the plug-in information array [object PluginArray] is used User preference product name secondary information of Gecko product language of operating system undefined browser user agent string Mozilla/5.0 (Windows NT 20030107) WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 operating system default language undefined user personal information object undefined browser brand Google Inc. Secondary information of browser vendor * / IV. DOM

DOM (document object Model) is an API for HTML and XML documents, which can be changed through DOM.

The DOM model treats the entire document (XML document and HTML document) as a tree structure and represents the document as a document object.

DOM specifies that each component in the document is a Node:

Document node (Document): represents the entire document

Element node (Element): a tag in the document

Text node (Text): text in markup

Attribute node (Attr): represents an attribute so that an element has an attribute

4.1, node type

All node types in 12 have a NodeType attribute to indicate the node type.

The node type description 1Element represents the element 2Attr represents the attribute 3Text represents the text content in the element or attribute. 4CDATASection represents the CDATA part of the document (text that is not parsed by the parser). 5EntityReference stands for entity reference. 6Entity represents an entity. 7ProcessingInstruction stands for processing instructions. 8Comment stands for comments. 9Document represents the entire document (the root node of the DOM tree). 10DocumentType provides an interface to the entity defined for the document 11DocumentFragment represents a lightweight Document object that can accommodate some part of the document 12Notation represents the symbol declared in the DTD.

Example:

DOM var div1 = document.getElementById ("div1"); console.log (div1.nodeType); / / Node type 1 Element represents element console.log (div1.nodeName); / / DIV node name var id = div1.getAttributeNode ("id"); / / get attribute node id console.log (id.nodeType) of div1; / / 2 Attr represents attribute console.log (id.nodeName); / / id node name

Results:

4.2. Node relationship

NodeType returns numeric value of node type (1x12) nodeName element node: tag name (uppercase), attribute node: attribute name, text node: # text, document node: # documentnodeValue text node: include text, attribute node: include attribute, element node and document node: nullparentNode parent node parentElement parent node tag element childNodes all child nodes children first layer child node firstChild first child node Node object form first child tag element lastChild last child tag element lastElementChild last child tag element previousSibling on a brother node previousElementSibling a brother tag element nextSibling next brother nextElementSibling next brother tag element childElementCount number of first-level child elements (excluding text nodes and comments) ownerDocument points to the document node of the entire document

Node relationship method:

Returns true when hasChildNodes () contains one or more nodes

Contains () returns true if it is a descendant node

References to isSameNode (), isEqualNode () incoming nodes and reference nodes return true for the same object

CompareDocumentPostion () determines the various relationships between nodes

Example:

DOM p1

P2

P3

Var div1 = document.getElementById ("div1"); console.log (div1.firstChild); / / Line wrapping console.log (div1.firstElementChild); / / p1 node var childs=div1.childNodes; / / all child nodes for (var iNode 0

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report