Get element knowledge

+Use a variable to save one or some elements in the page

+There are two types of methods to get elements

1. Get unconventional elements

=> html: document.documentElement

=> head: document.head

=> body: document.body

2. Get general elements

2-1. Get element by id

=>Syntax: document Getelementbyid ('element id name ')

=>Return value:

->If there is an element corresponding to id on the page, it is this element

->If there is no element corresponding to id on the page, it is null

2-2. Get element by class name

=>Syntax: document Getelementsbyclassname ('element class name ')

=>Return value: * * must be a pseudo array**

->If there are elements corresponding to the class name on the page, how many are obtained and returned in the pseudo array

->If there is no element corresponding to the class name on the page, it is an empty pseudo array

2-3. Get element by tag name

=>Syntax: document GetElementsByTagName ('tag name ')

=>Return value: * * must be a pseudo array**

->If there are elements corresponding to the tag name on the page, how many are obtained and returned in the pseudo array

->If there is no element corresponding to the tag name on the page, it is an empty pseudo array

2-4. Get * * a * * tag according to the selector

=>Syntax: document Queryselector ('selector ')

=>Return value:

->If there is an element corresponding to the selector on the page, the first element corresponding to the selector is returned

->If there is no element corresponding to the selector on the page, it is null

2-5. Obtain * * a set of * * tags according to the selector

=>Syntax: document Queryselectorall ('selector ')

=>Return value: * * must be a pseudo array**

->If there are elements corresponding to selectors on the page, how many are obtained and returned in a pseudo array

->If there is no element corresponding to the selector on the page, it is an empty pseudo array

// 1. Get unconventional elements

// 1-1. html

// console.log(document.documentElement)

// 1-2. head

// console.log(document.head)

// 1-3. body

// console.log(document.body)

// 2. Get general element

// 2-1. Get by id

// var ele = document.getElementById('box')

// console.log(ele)

// 2-2. Get by class name

// var eles = [ ...document.getElementsByClassName('box') ]

// console.log(eles)

// 2-3. Get by tag name

// var eles = document.getElementsByTagName('div')

// console.log(eles)

// 2-4. Get one through selector

// var ele = document.querySelector('li:nth-child(3)')

// console.log(ele)

// 2-5. Get a set through a selector

// var eles = document.querySelectorAll('.box')

// console.log(eles)

//Traversal

// for (var i = 0; i < eles.length; i++) {

// console.log(eles[i])

// }

//forEach, querySelectorAll. The element collection obtained by this method can be directly used for each

// eles.forEach(function (item) {

// console.log(item)

// })

!DOCTYPE html>
<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>Document</title>
</head>
<body>

  <div id="box1"></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>

  <div class="box">div</div>

design sketch

Properties of the action element

Label attribute: attribute name = attribute value

Label attribute classification:

1. Native attributes

=>Some attribute names in W3C specification

=>For example: id class style type src href

2. Custom attributes

=>The attribute names that are not in the W3C specification are written on the label by ourselves

3. H5 custom attribute

=>Purpose: it is to distinguish the forms written on the label from the original travel

=>Requirement: when writing H5 custom attributes, start with data -

=>Example: Data Hello = "world"

->Data - indicates the flag of H5 custom attribute

->Hello represents the property name

->World represents the attribute value

Action element attribute

1. Operation native attribute

+Syntax: elements Attribute name = attribute value

+Note: if boolean type attribute is encountered, you can use true or false assignment

2. Operation custom attribute (non H5 custom attribute)

+Settings:

=>Syntax: elements setAttribute(key, value)

+Delete:

=>Syntax: elements removeAttribute(key)

+Get:

=>Syntax: elements getAttribute(key)

=>Return value: this element specifies the value of the custom attribute

+Note: native attributes can be manipulated, but it is not recommended and should not be used to delete native attributes

3. Operate H5 custom attribute

+Each element node has an inherent attribute called dataset

+It is a data structure similar to an object, which stores all H5 custom attributes on the tag

+The operation of H5 custom attribute is the operation of the data structure of dataset (the same as the object operation syntax)

// 0. Get element

var ele = document.querySelector('div')

var img = document.querySelector('img')

var inp = document.querySelector('input')

var btn = document.querySelector('button')

// 1. essential attribute

//Action id attribute

// console.log(ele.id)

//Set id attribute

// ele.id = 'container'

// btn.onclick = function () {

// console.log(inp.type)

// if (inp.type === 'text') {

// inp.type = 'password'

// } else {

// inp.type = 'text'

// }

// }


 

// 2. Custom properties

// 2-1. set a property

// ele.setAttribute('gx', 100)

// 2-2. Delete attribute

// ele.removeAttribute('id')

// 2-3. get attribute

// var res = ele.getAttribute('gx')

// console.log(res)

// console.log(typeof res)


 

// 3. H5 custom attributes

console.log(ele.dataset)

//Add:

ele.dataset.aaa = 100

//Delete:

delete ele.dataset.hello

//Change:

ele.dataset.aaa = 300

//Check:

console.log(ele.dataset.id)

Case: select all

<!DOCTYPE html>
<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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 100px;
      padding: 20px;
      margin: 50px auto;
      border-radius: 10px;
      border: 2px solid #333;
    }

    hr {
      margin: 10px 0;
    }
  </style>
</head>
<body>

  <div class="box">
    <input class="all" type="checkbox"> Select all
    <hr>
    <input class="item" type="checkbox"> Option 1 <br>
    <input class="item" type="checkbox"> Option 2 <br>
    <input class="item" type="checkbox"> Option 3 <br>
    <input class="item" type="checkbox"> Option 4 <br>
  </div>

  <script>
    /*
      Select all

      Requirements:
        1. Click operation of select all button
          => When the select all button is selected, all option buttons are also selected
          => When the select all button is unselected, all option buttons are also unselected
        2. Click the operation of each option button
          => When each option button is clicked, it needs to be judged
          => If all option buttons are selected, the select all button is selected
          => As long as any option button is unselected, the select all button is unselected
    */

    var allBtn = document.querySelector('.all')
    var items = [ ...document.querySelectorAll('.item') ]

    // 1. Click the select all button
    allBtn.onclick = function () {
      items.forEach(function (item) { item.checked = allBtn.checked })
    }

    // Question: when does the effect appear?
    //  When you click the select all button, you need to bind the click event to the select all button
    // allBtn.onclick = function () {
    //   //Question 2: what do you need to get?
    //   //The select all button has its own selected status, a native attribute, checked
    //   var self = allBtn.checked

    //   //Question 3: for whom? Give each option button
    //   //self is true. Set the checked property to true for each option button
    //   //self is false. Set the checked attribute to false for each option button
    //   items.forEach(function (item) { item.checked = self })
    // }


    // 2. Click each option button
    // Question 1: to whom do you bind click events? Each option button
    items.forEach(function (item) { item.onclick = handler })
    function handler() {
      allBtn.checked = items.every(function (item) { return item.checked })
    }



    // Event handler
    // function handler() {
    //   //Question 2: whose attribute do I want to get?
    //   //Get the selected status of all option buttons
    //   //Take this question as an example. Only when I get 4 trues can I select true by the select all button
    //   //As long as there are not four true buttons, the select all button is unchecked false
    //   //Count the number of true in the four option buttons
    //   var total = 0

    //   items.forEach(function (item) {
    //     if (item.checked) total++
    //   })
    //   //After the loop ends, total is the number with chekced as true
    //   // console.log(total)

    //   //Judge
    //   //If total = = = items If length is true, it means that all are selected, and the select all button is set to true
    //   //If total = = = items If the length is false, at least one is unselected, and the select all button is set to false
    //   allBtn.checked = total === items.length
    // }

    // function handler() {
    //   //Question: the core purpose is to know whether they are all true
    //   //Every item returns true only when every item is true. As long as any item is false, it will return false
    //   //But every is an array method, and items cannot be used
    //   var res = items.every(function (item) { return item.checked })

    //   //Assign res directly to checked of allBtn
    //   allBtn.checked = res
    // }
  </script>
</body>
</html>

Renderings:

Action element style

+There are three styles of operating elements in JS

1. Get element inline style (only inline style can be obtained)

2. Get element non inline style (including inline and non inline)

3. Set the style of the element (only the inline style can be set)

+Note: when it comes to style names with dashes

=>Conversion to hump nomenclature

var ele = document.querySelector('div')

=>Use array Association syntax

// 1. Get element inline style

//Syntax: elements style. Style name

// console.log(ele.style.width)

// console.log(ele.style.height) / / non inline style

// console.log(ele.style.fontSize)

// console.log(ele.style['font-size'])

// 2. Get element non inline style

//Syntax: window Getcomputedstyle (the element to get the style) Style name

// console.log(window.getComputedStyle(ele).width)

// console.log(window.getComputedStyle(ele).height)

// console.log(window.getComputedStyle(ele).fontSize)

// console.log(window.getComputedStyle(ele)['background-color'])

// 3. Set element style (only inline style can be set)

//Syntax: elements style. Style name = style value

// ele.style.backgroundColor = 'red'

Case: back to the top

<!DOCTYPE html>
<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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      height: 5000px;
    }

    .header {
      width: 100%;
      height: 60px;
      font-size: 40px;
      background-color: skyblue;
      color: #fff;
      text-align: center;
      line-height: 60px;
      position: fixed;
      left: 0;
      top: -60px;

      transition: top .5s linear;
    }

    .goTop {
      position: fixed;
      right: 50px;
      bottom: 50px;
      width: 50px;
      height: 50px;
      font-size: 20px;
      line-height: 25px;
      text-align: center;
      background-color: pink;
      color: #fff;
      cursor: pointer;

      display: none;
    }
  </style>
</head>
<body>

  <div class="header">Top bar</div>
  <div class="goTop">Back to the top</div>

  <script>
    /*
      Case - back to top

      Requirements:
        1. Appearance of content
          => When the page scrolls above the critical point (350)
            -> header Setting top style to 0 appears
            -> goTop Set the display style to block appears
          => When the page scrolls below the critical point (350)
            -> header Hide set top style to - 60px
            -> goTop Hide set the display style to none
        2. Back to the top
          => When you click the goTop button
          => Let the scroll bar scroll back to the top
    */

    // 0. Get element
    var header = document.querySelector('.header')
    var goTop = document.querySelector('.goTop')

    // 1. Appearance of content
    // Question 1: when does the effect appear? The effect appears as the scroll bar changes
    // Bind scroll event to browser
    window.onscroll = function () {
      // Question 2: by what judgment? Browser roll height
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop

      // judge
      if (scrollTop > 350) {
        header.style.top = 0
        goTop.style.display = 'block'
      } else {
        header.style.top = '-60px'
        goTop.style.display = 'none'
      }
    }


    // 2. Back to the top
    goTop.onclick = function () {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  </script>
</body>
</html>

Operation element class name

+Purpose: batch change style

1. className

+Is the operation of native attributes

+Because there is a keyword called class in JS, it is renamed className in order to avoid it

+Note: the value of the class name is a string. Yes, but the string may contain multiple class names

2. classList

+Each element node has an attribute called classList

+Is a data structure similar to an array, which stores all the class names of the element

+Addition, deletion, modification and query are all operations on the classList, and special APIs are given

+Add: element classList. Add (class name)

+Delete: element classList. Remove (class name)

+Switching: elements classList. Toggle (class name)

->Delete the original and add the original

var ele = document.querySelector('div')

// 1. className

// 1-1. Get element className

// console.log(ele.className)

// 1-2. Set element className = 'value'

//Because it is assigned by the equal sign (=), when you assign a value, you will overwrite all the original ones

// ele.className = 'box'

// 1-3. Append element className + = 'value' / / there is a space after the equals sign

// ele.className = ele.className + ' box'

// 2. classList

console.log(ele.classList)

// 2-1. increase

ele. classList. Add ('box ') / / boxno class name

// 2-2. delete

ele.classList.remove('c') //c is the class name

// 2-3. switch

ele.onclick = function () {

ele.classList.toggle('active') //active is the class name

}

<!DOCTYPE html>
<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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    div {
      width: 100px;
      height: 100px;
      background-color: pink;
    }

    div.active {
      width: 200px;
      height: 200px;
      background-color: skyblue;
      border-radius: 50%;
    }
  </style>
</head>
<body>

  <div class="a b c d"></div>

  <script>
    

    var ele = document.querySelector('div')

    // 1. className
    // 1-1.  Get element className
    // console.log(ele.className)
    // 1-2.  Set element className = 'value'
    // Because it is assigned by the equal sign (=), when you assign a value, you will overwrite all the original ones
    // ele.className = 'box'
    // 1-3.  Append element className + = 'value' / / there is a space after the equals sign 
    // ele.className = ele.className + ' box'

    // 2. classList
    console.log(ele.classList)
    // 2-1.  increase
    ele.classList.add('box')  //box does not have a class name
    // 2-2.  delete
    ele.classList.remove('c')   //c is the class name
    // 2-3.  switch
    ele.onclick = function () {
      ele.classList.toggle('active')   //active is the class name
    }




  </script>
</body>
</html>

design sketch:

Operation element content

1. innerText

+A read-write attribute

+Read:

=>Syntax: elements innerText

=>Get: all text contents in this element

+Write:

=>Syntax: elements 'innerText =' value

=>Function: write the text content in the label completely

=>Note: there is no way to recognize and parse html format strings

2. innerHTML

+A read-write attribute

+Read:

=>Syntax: elements innerHTML

=>Get: all the contents of the element (including hypertext) are given to you in the form of an html format string

+Write:

=>Syntax: elements innerHTML = 'value'

=>Function: write the hypertext content in the label completely

=>Note: you can recognize and parse html format strings

3. value

+A read-write attribute is actually the operation of the native attribute value

+Read:

=>Syntax: form elements value

=>Get: the value value of the form element

+Write:

=>Syntax: form elements Value = 'value'

=>Function: set the value of form element

<!DOCTYPE html>
<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>Document</title>
</head>
<body>

  <div>
    hello
    <p>Hello world</p>
    world
  </div>

  <input type="text">

  <script>
 

    // Get element
    var ele = document.querySelector('div')
    var inp = document.querySelector('input')

    // 1-1. innerText get
    // console.log(ele.innerText)
    // 1-2. innerText settings
    // ele. InnerText = '< H1 > I'm new < / H1 >'

    // 2-1. innerHTML get
    // console.log(ele.innerHTML)
    // 2-2. innerHTML settings
    // ele. InnerHTML = '< H1 > I'm new < / H1 >'

    // 3-1. value setting
    inp.value = 'I'm new here'
    // 3-2. value acquisition
    console.log(inp.value)

  </script>
</body>
</html>

Renderings:

Keywords: Javascript Front-end

Added by moehome on Mon, 07 Mar 2022 03:20:04 +0200