BOM browser object model, DOM document object model

Keywords: Javascript ECMAScript

1, BOM browser object model

BOM - Browser Object Model
The top-level object of BOM is winodw (an object. When you open a page, there is a window)
All the variables you define in the group are under window.

1. Window size of browser

Refers to the size of the browser's visual window.
A scroll bar may appear in the browser
        In a normal browser, the scroll bar is part of the browser
       On the MAC, it doesn't count.
The innerHeight and innerWidth properties contain the size of the scroll bar

1.1 get the height of the browser

innerHeight

console.log(window.innerHeight)
//window can be omitted without writing
//console.log(innerHeight)

1.2 get the width of the browser

innerWidth

console.log(window.innerWidth)
//window can be omitted without writing
// console.log(innerWidth)

2. Pop up layer of browser

In the BOM, we are provided with three pop-up layers
The three have in common:
Will block the continuation of the program
     Because JS is single threaded
     If the user does not click the button, it means that the current pop-up layer has not ended
The code will not continue to execute downward until the user operates

2-1 alert box

Pop up a prompt text
There is only one OK button
Syntax: window.alert('prompt text ')
Return value: undefined

var res = windoe.alert('Draw a beautiful yarn')
console.log(res)

2-2 confirm selection box

Pop up a prompt text
There are two buttons: OK and cancel
Syntax: window.confirm('prompt text ')
Return value: Boolean
                true when the user clicks OK
                When the user clicks cancel, it is false

var res = windwo.confirm('Draw a beautiful yarn')
console.log('res')

2-3 prompt input box

Pop up a prompt text
There is an input field
There are OK and Cancel buttons
Syntax: window.prompt('prompt text ')
Return value:
                If the user clicks OK, it is the content in the text box
                If the user clicks cancel, it is null

var res = window.prompt('Draw a beautiful yarn')
console.log(res)

3. Address bar of browser

3-1 what does the address bar contain

http://www.baidu.com?a=100&b=200#abc
Transport protocol: http
Function: the way the front and back end interact
Domain name: www.baidu.com
Function: find a server computer
Query string:? a=100&b=200
It doesn't affect you to open this page
Function: information carried when opening this page
Hash: #abc
Action: anchor positioning

3-2 location object

There is a member called location under the window.
location is an object that stores information related to the content of the web address bar.

(1)hash

Hash value
Action: anchor positioning

(2) href

Address bar information
Read: get the current address bar address
Write: modify the current address bar address (jump page)

(3) search

Query string
Function: bring some information when you come to this page

3-3 reload() method

Syntax: window.location.reload()
Function: reload the current page
It is equivalent to pressing the refresh button in the upper left corner of the browser
Note: it cannot be written where it can be executed by opening the page

4. Browser history

Operate the forward and backward of the browser
There is a member called history under window, which is an object that contains some properties and methods of operation history.

4-1 back()

Syntax: window.history.back()
Function: back to the previous history.
Premise: you need to have a history, or you won't have to go back.

4-2 forward()

Syntax: window.history.forward()
Function: advance to the next history.
Premise: you need to go back before you can operate.

4-3 go()

Syntax: window.history.go (integer)
Positive integer: indicates advance
0: refresh the current page
Negative integer: indicates backward

5. Browser version information

There is a member called navigator under the window, which is an object that stores the version information of the browser.

5-1 userAgent

Represents the version information and model information of the browser

console.log(window.navigator.userAgent)

5-2 appName

All browsers have the same name netscape
Internet Explorer is also netscape
IE lower version is not

console.log(window.navigator.appName)

5-3 platform

Indicates the operating system of the browser

console.log(window.navigator.platform)

6. Common browser events

6-1 window.onload = function () {}

Execute after all resources on the page are loaded
Function: JS front
When you need to write JS code in the head tag, you'd better add a window.onload after it

 	window.onload = function () {
       console.log('Resource loading completed')
     }

6-2 window.onscroll = function () {}

Triggered when the browser scroll bar scrolls
Whether horizontal or vertical, as long as the scroll is triggered
effect:

  1. Floor navigation
  2. Tips for the top notification bar and the back to top button
  3. Asymptotic display page
  4. Waterfall flow
	window.onscroll = function () {
       console.log('Scroll bar scroll again')
     }

6-3 window.onresize = function () {}

Triggered when the browser visual window changes
As long as the change will trigger
The screen size is generally determined by combining innerWidth and innerHeight
Mobile end: horizontal screen
Responsive layout: determining window size

	window.onresize = function () {
      console.log('The browser visual window has changed size')
    }

7. Height and width of browser scrolling

When the page is wider or higher than the window, part of it will be hidden with scrolling
What we call hidden above is the height of the roll
What we call hidden on the left is the width of the roll

7-1 get the height of the roll off

(1)document.documentElement.scrollTop

You must have a DOCTYPE label when using

window.onscroll = function () {
      console.log('html', document.documentElement.scrollTop)
    }

When scrolling the scroll bar, the height of the page is hidden, and what is printed is the hidden height

(2)document.body.scrollTop

No DOCTYPE label must be used

window.onscroll = function () {
	console.log('body', document.body.scrollTop)
}

(3) Compatible writing

var scrollTop = document.documentElement.scrollTop || document.body.scrollTop

=> || Used as a short circuit expression or
    -> When the front is true When, Then return the previous value directly
    -> When the front is false When, Then return the following value, Whether it's in the back or not false
window.onscroll = function () {
	  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      console.log(scrollTop)
    }

7-2 get the width of the roll out

(1)document.documentElement.scrollLeft

You must have a DOCTYPE label when using

window.onscroll = function () {
	console.log('have ', document.documentElement.scrollLeft)
}

(2)document.body.scrollLeft

No DOCTYPE label must be used

window.onscroll = function () {
	console.log('No, ', document.body.scrollLeft)
}

(3) Compatible writing

var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft

=> || Used as a short circuit expression or
    -> When the front is true When, Then return the previous value directly
    -> When the front is false When, Then return the following value, Whether it's in the back or not false
window.onscroll = function () {
	var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
	console.log(scrollLeft)
}

8. Short circuit expression

8-1 or (|)

Function: you can use the | operator to split two expressions. If the result of the previous expression is true, the latter will not be executed; Only when the front is false will the following expression be executed.

When you use 𞓜 short circuit expression to assign values:
          When the previous expression is true, the result of the previous expression will be obtained;
          When the previous expression is false, the result of the following expression will be obtained (whether the result of the following expression is true or false)

8-2 & &)

Function: you can use the & & operator to split two expressions. If the result of the previous expression is true, the later expression will be executed (if the result of the previous expression is false, the latter expression will not be executed).

When you use & & short circuit expression to assign values:
          When the previous expression is true, the result assignment of the following expression is directly calculated;
          When the previous expression is false, the previous result is returned directly.

2, DOM document object model

DOM -- Document Object Model
DOM is a tree structure of content

The top level of DOM is document, which represents the current document
Because our PC side documents are inserted into the browser to run, there is also a window above the document on the PC side
Note: there is a document under the window

1. Get DOM elements

Get the elements in the page through JS

1-1 unconventional labels

(1)html

Syntax: document.documentElement

	var html = document.documentElement
    console.log(html)

(2)head

Syntax: document.head

	var head = document.head
    console.log(head)

(3)body

Syntax: document.body

	var body = document.body
    console.log(body)

1-2 general label

The following example shows the code in the body tag

<body>

  <li>1</li>
  <li class="active">2</li>
  <li class="active" id="abc">3</li>
  <li class="active aaa">4</li>

  <button id="btn">Button</button>

  <p id="a">outside</p>

  <div id="box">
    <p id="a">inside</p>
  </div>

  <ul>
    <li class="box">1</li>
    <li class="box">2</li>
    <li class="box">3</li>
    <li class="box">4</li>
    <li class="box">5</li>
    <li class="box">6</li>
    <li class="box">7</li>
    <li class="box">8</li>
    <li class="box">9</li>
    <li class="box">10</li>
  </ul>

  <input type="text" name="username">
  <input type="text" name="username">
  <div name="username">123</div>

</body>

(1)getElementById()

Syntax: lookup range. getElementById('id name ')
Search scope: document or an element
Return value:
              If there is an element with this id matching, it is this element
              If there is no element matching this id, it is null

	var btn = document.getElementById('btn')
    console.log(btn)

(2)getElementsByTagName()

Syntax: lookup range. getElementsByTagName('tagname ')
Return value: a pseudo array (common array methods cannot be used)
              If there are elements with this tag name matching, how many are obtained
              If there is no element matching this tag, an empty pseudo array is returned

    var box = document.getElementsByTagName('p')
    console.log(box)
    // If you want to get an element accurately, you can either traverse it or use [index]
	// var div = document.getElementsByTagName('div')[0]
	//console.log(div)
	// Find multiple elements called p by tag name under div scope
	// var p2 = div.getElementsByTagName('p')
	//console.log(p2)

(3)getElementsByClassName()

Syntax: lookup range. getElementsByClassName('class name ')
Return value: is a pseudo array
              If there are elements with matching class names, how many are obtained
              If there is no element matching the class name, an empty pseudo array is returned

    var box = document.getElementsByClassName('box')
    console.log(box)

(4)getElementsByName()

Syntax: lookup range. getElementsByName('value of element name attribute ')
Return value: is a pseudo array
              If the value of the name attribute of an element matches, how many are obtained
              If no value of the name attribute of the element matches, it is an empty array

    var inp = document.getElementsByName('username')
    console.log(inp)

(5)querySelector()

Syntax: lookup range. querySelector('selector ')
Selectors: selectors that can be written in CSS can be written here
Return value:
              If an element matching the selector is found, the first found content is returned
              If there is no element matching the selector, null is returned
Features: not supported by IE lower version

    var box = document.querySelector('ul > li:nth-child(2)')
    console.log(box)

(6)querySelectorAll()

Syntax: lookup range. querySelectorAll('selector ')
Selectors: selectors that can be written in CSS can be written here
Return value:
              If you find elements that match the selector, get as many as you have
              If there is no element matching the selector, an empty pseudo array is returned
Features: not supported by IE lower version

    var box = document.querySelectorAll('ul > li:nth-child(odd)')
    console.log(box)

2. Operation element attribute

Attribute of element
id / class / style / src / type / name / href / border /... - called a native attribute
Style is the attribute name. The function of this attribute is to set the inline style for the element
index / abc / aaa /... - custom attribute
It is not a native attribute of the tag, but an attribute we write casually
Attributes starting with data XXX - we all call H5 custom attributes

2-1 native attributes

The native attribute is a read-write attribute
Syntax: element. Attribute name
Read: element. Attribute name -- get the value of the attribute of the element
Write: element. Attribute name = 'value' - set the value of the attribute of the element
Note: except class, the operation class name uses the element. className

<body>
  <div data-a="100" abc="123"></div>
  <input type="text">
  <img src="" alt=""
</body>
    var div = document.querySelector('div')
    var inp = document.querySelector('input')
    // Set an id attribute for the div
    div.id = 'box'
    // Read the id attribute on the div
    console.log(div.id)
    console.log(div)
    // Set the type attribute for input
    inp.type = 'password'

Set an id attribute for the div

Read the id attribute on the div

Set the type attribute for input

2-2 custom attributes

You cannot click syntax directly

(1) setAttribute('attribute name ',' attribute value ')

Set attributes on element labels

    var div = document.querySelector('div')
    var inp = document.querySelector('input')
    // Set custom properties
    div.setAttribute('index', 100)
    div.setAttribute('id', 'box')

Set custom properties

(2) getAttribute('attribute name ')

Gets the value of the attribute on the element

    // Get custom properties
    var str = div.getAttribute('index')
    console.log(str)

(3) removeAttribute('attribute name ')

Delete attribute on element

    // Delete custom attribute
    div.removeAttribute('abc')

(4) Characteristics of the three methods

You can operate custom attributes or native attributes;
No matter what data type you set, when you get it from the label again, it is a string.

2-3 H5 custom attributes

Each element has an attribute called dataset
It contains all H5 custom attributes
     key is the content other than data -
     Value is the value of this attribute

Custom properties for action H5

You can operate directly in the dataset
Get: element. dataset. Name
     Name: write data-a on the label and use a
Setting: element. dataset. Name = 'value'
     Name: if you write a here, the mapping on the label is data-a

    // Gets the data-a attribute on the element tag
    var str = div.dataset.a
    console.log(str)

    // Set the data Hello attribute on the element label and set the value to world
    div.dataset.hello = 'world'

    // Delete the data Hello attribute on the element tag
    // Directly delete the hello member in the dataset object
    delete div.dataset.hello

3. Operation element class name

3-1 operate according to the original genus

Set class name: element. className = 'class name you want to set'

Modify class name: element. className = 'new value'

Append class name: element. className = element. className + 'new class name'
Note: there should be a space in front of the new class name

Delete class name: get the class name

  • Intercept string
  • Cut according to the space, cycle through, find the one you want to delete, and delete it
  • Write it again
<style>
    div {
      width: 100%;
      height: 50px;
      /* background-color: skyblue; */
      /* display: none; */
      position: absolute;
      top: -50px;
      left: 0;
      background-color: skyblue;
      transition: top .5s linear;
    }

    div.box {
      /* background-color: pink; */
      /* display: block; */
      top: 0;
    }

    button {
      margin-top: 100px;
    }
  </style>
<body>
  <button>Button</button
  <div class="a b c d e f g h i j">I am div label</div>
</body>
    // 0. Get element
    var div = document.querySelector('div')
    // 1. Operation class name in native attribute mode
    // 1-1. Set class name
    div.className = 'box'

    // 1-2. Modify class name
    div.className = 'box2'

    // 1-3. Add class name
    div.className += ' abc'

3-2 API provided by H5 standard

The element has an attribute called classList, which contains the class names set on all elements. This classList provides a series of methods to operate

(1) add()

Syntax: element. classList.add('class name you want to add ')

(2) remove()

Syntax: element. classList.remove('class name you want to remove ')

(3) toggle()

Syntax: element. classList.toggle('name of class you want to switch ')
             When the element has this class name, it is deleted
             When the element does not have this class name, it is added

	// Get element
    var div = document.querySelector('div')
	// Add class name
    div.classList.add('box')
    
    //Delete class name
    div.classList.remove('h')
    
    // Change class name
    var btn = document.querySelector('button')
    btn.onclick = function () {
    	// When this code is executed, if the div does not have a box class name, it will be added
		// When executing this code, if the div has a box class name, it will be deleted
     	div.classList.toggle('box')
    }

4. Operation element text content

4-1 innerHTML

Read write properties
Read: get all the contents inside the element
         Text + label all contents
         Syntax: element. innerHTML
         Returns as a string
Write: sets the hypertext content inside the element
         Syntax: element. innerHTML = 'what you want to set'
         When the html structure appears in your string, it will be parsed automatically

<body>
	<div>
		hello world
		<p>Hello world</p>
		hello world
	</div>
</body>
    // Get element
    var div = document.querySelector('div')
    var inp = document.querySelector('input')
    // Gets the hypertext content of the element
    var str = div.innerHTML
    console.log(str)
    console.log(typeof str)
    // Sets the hypertext content of the element
    div.innerHTML = '<span>I'm new</span>'

Gets the hypertext content of the element

Set the hypertext content of the element (overwritten writing)
The label is automatically resolved

4-2 innerText

Read write properties
The text content of the action element
Read: get all text content inside the element
         Include the text content of all descendant elements of child elements
         Label content is not obtained (only text content is obtained)
         Syntax: element. innerText
Write: sets the text content inside the element
         Full coverage write
         Syntax: element. innerText = 'what you want to set'
         When html structure appears in your string, it will not be parsed automatically

    // Get element
    var div = document.querySelector('div')
    var inp = document.querySelector('input')
    // Gets the text content of the element
    var str = div.innerText
    console.log(str)
    // Sets the text content of the element
    div.innerText = '<span>I'm new</span>'

Gets the text content of the element

Set the text content of the element (overwritten writing)
Tags are not automatically parsed and are treated as part of the text

4-3 value

Read write properties
Operate on the value attribute of the form element
Read: get the value attribute of the form element
         Syntax: element. value
Write: set the value attribute of the form element
         Syntax: element value = 'what you want to set'

    // Get element
    var div = document.querySelector('div')
    var inp = document.querySelector('input')
    // Set the value of the element
    inp.value = 'Hello world'
    // Gets the value of the element
    var str = inp.value
    console.log(str)

Set the value of the element

Gets the value of the element

Posted by fireice87 on Sat, 20 Nov 2021 10:15:19 -0800