search
HomeWeb Front-endJS TutorialImplement the composition of JavaScript (detailed interpretation of BOM and DOM)

Below I will bring you an article on how to implement JavaScript (detailed interpretation of BOM and DOM). Now I share it with you and give it as a reference.

We know that a complete JavaScript implementation needs to be composed of three parts: ECMAScript (core), BOM (Browser Object Model), and DOM (Document Object Model).

BOM:

BOM provides many objects for accessing browser functions that have nothing to do with the content of the web page (these are DOM ), currently, BOM has been moved into the HTML5 specification by W3C.

window object:

The core of BOM represents an instance of the browser. It is both an interface for accessing the browser window through javascript and a Global specified by ECMAScript. Object, which means any object, variable and function defined in the web page, has window as its Global object, and therefore has access to methods such as paresinInt(). (Excerpted from Height Three). In addition, if a web page contains frames, each frame has its own window object and is stored in the frames collection (starting at index 0, ltr, ttb).

First of all, the variables and functions in the global execution environment are all properties and methods of the window object. Of course, there is a slight difference between global variables and the directly defined window property type. Global variables (to be precise, explicitly declared global variables) cannot be deleted, but the window property can. In addition, there is another detail to note. Trying to access undeclared variables will cause an error, but there is no problem using the query window object.

So, what are the common properties or methods of window?

1.name, each window object has a name attribute, which contains the name of the frame. Usually to understand window relationships and frames.

2. Window position method: moveTo (x coordinate of new position, y coordinate of new position), moveBy (move x horizontally, move y vertically). These two methods are not applicable to the framework.

3. Window size attribute: innerWidth/Height (size of the view area (minus the width of the border)/* IE, Safari, firefox */), outerWidth/Height (returns the size of the browser window/* IE, Safari, firefox */). In Chrome, inner and outer both return the size of the view area.

Of course, you can change the window size through resizeTo (new window width, new window height), resizeBy (increase x than the original width, increase y than the original height). This love song method does not apply to frame structures.

4.window.open(URL, window target, attribute string, boolean whether the new page replaces the currently loaded page in the browser history) is used to navigate to a specific URL or open a new window . If a window target is specified and the window target is the name of an existing window or frame, the specified url will be loaded in the renamed window or frame. Otherwise, the new window that opens is named the target window. Of course, the keywords that can be specified for the window target include _self, _parent, _top, and _blank.

<a href=http://www.jb51.net>click me</a>
    <script>
    var link=document.getElementsByTagName("a")[0];
      alert(link.nodeName);   
     window.onload=function(){
      
      link.onclick=function () {
        window.open(link.href,"good","width=400px,height=300px");
        return false;
    
      }  
    }
  </script

The specific settings of the characteristic string here will not be described in detail. Those who are interested can click here

5. As a single-threaded language, js still allows setting the timeout value (specified Execute code after the event) and interval time value (cycle every specified time) to schedule code execution at a specific moment.

Timeout call: setTimeout (js code string, millisecond time). As a single-threaded language, the js task queue can only execute one piece of code at a time. If the task queue is empty after the set time interval, Then execute the code string, otherwise, wait until the previous code execution is completed before executing.

var al=setTimeout(function () {
      alert("good");
    },5000);
    alert(al); //2

Here, I called an anonymous function to output good after 5 seconds, and a warning box popped up in the window to display 2. It can be seen that the setTimeout() function returns a numerical ID, which is unique, then we You can use this ID to clear the timeout call, and you can use clearTimeout(ID) to clear it.

Indirect call: setInterval(), it accepts the same parameters as setTimeout(), and also returns a numerical ID, which can be cleared using clearTimeout().

6. System dialog box methods: alert(), confirm(), prompt(), etc. are written in my previous blog, click here

location object

Rather than being an object in the BOM, it is better to say that Location is an attribute in the window object. Of course, it is also an attribute of the document object in the DOM that will be discussed later, that is, window.location and document. location refers to the same object.

Location object attribute list. Modifying these attributes can load a new page and generate a new record in the history. Using location.replace() will not generate new records in the history.

##href"www.google.com"Returns the complete url of the current page, calling assign()pathnameportprotocolsearch

navigator object: The de facto standard used to identify browsers. Its properties and methods are mainly used to detect the type of browser.

The rest, such as the history object (save historical records) and the screen object (indicates the client's capabilities), are not useful in programming in js, so they will not be described in detail.

-------------------------------------------------- ----------------------------------

DOM:

DOM is an API based on XML and extended for HTML. DOM relies on node tree expansion.

First of all, we need to make it clear that the document node is the root node of each node. The document node has and has only one child node, which is the element html (document element).

Node type:

An interface in DOM1, implemented by all DOM node types (text nodes, attribute nodes, element nodes), this interface is used in js as Node type implementation.

nodeType attribute, owned by each node. Represented by 12 numerical values, element--1, attribute--2, text--3...

nodeName attribute. For element nodes, the value of nodeName is the label name.

nodeValue attribute, for element nodes, the value of nodeValue is null.

Node relationship: Each node has a childNodes attribute and saves a NodeList (like array object) object. Each node has a parentNode attribute that points to the parent node. The nodes in childNodes have the same parentNode. Sibling nodes can be accessed using the previousSibling and nextSibling properties. At the same time, childNodes[0]==firstChild, childNodes[childNodes.length-1]==lastChild.

Operation node: appendChild(), push a node to the end of NodeList, and return the newly added node. insertBefore(), unshifts a node to the head of NodeList and returns the newly added node. replaceChild(newChild,targetChild), replaces the target node. The original node is still in the document, but has no position. removeChild(tragetChild), removes nodes, has a similar effect to replaceChild(). cloneChild(boolean), true means complete copy (entire node and child nodes), false means basic copy.

Document type:

represents the document. The document object is an instance of HTMLDDocument (inherited from the Document type) and represents the entire html page. At the same time, the document object is also a property of the window object, so it can be accessed as a global object. document.firstChild==html. document.body==body. document.doctype--->Reference to . document.title--->title document.url--->location.url.

Find elements: getElementById(),getElementsByTagName(),getElementsByClassName().

Document writing Input: write(), writeln(), open(), close()

Element type:

getAttribute(), to get attributes for class, use " class", instead of className, you can get the class attribute when using element.className.

setAttribute(), set the attribute, and replace it if the attribute exists. Otherwise, create.

removeAttribute(), completely remove element attributes.

createElement(), creates a new element.

Text type:

createTextNode(), creates a text node. If two text nodes are adjacent sibling nodes, the two texts will be connected, no Space.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Basic specifications of JavaScript

Basic usage of Javascript

## Sample code for creating fireworks special effects using p5.js_javascriptTips

hash "#contents" Returns the hash in the url, There is no response for ""
##host "www.google.com" Return the server name and port number (if any)
hostname "www.google.com " Returns the server name without the port number
##''/wileyCDA/' Return directory name
"8080" Returns the port number, if not, returns an empty string
"http:" The protocol used by the return page
"?=javascript" Returns the query string, starting with a question mark

The above is the detailed content of Implement the composition of JavaScript (detailed interpretation of BOM and DOM). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.