JS-DOM

refer to: https://www.udemy.com/course/the-web-developer-bootcamp/


 

Document Object Model - JS

  • The DOM is a JavaScript representation of a webpage
  • It's your JS "window" into the contents of a webpage
  • It's just a bunch of objects that you can interact with via JS.

Document

  • The document object is our entry point into the world of the DOM. It contains representations of all the content on a page, plus tons of useful methods and properties.

SELECT

  1. document.getelementById('id')
  2. document.getelementByTagName('TagName')
  3. document.getelementByClassName('ClassName')
  • getElementById
    • function changeColor(newColor) {
        var elem = document.getElementById('para');
        elem.style.color = newColor;
      }
  • getElementByTagName
  • getElementByClassName

querySelector,找到并返回第一个匹配项

querySelectorAll,找到所有匹配项的合集

根据id找,属性值前面加#; 根据class找,属性值前面加.  

  • // finds first h1 element
    document.querySelector('h1');
    
    //finds first element with ID of red
    document.querySelector('#red');
    
    //find first element with Class of big
    document.querySelector('.big');
    
    //find the input element whose type is checkbox
    document.querySelector("input[type = 'checkbox']");

MANIPULATE

  • innerHTML, textContent/innerText

        change innerText

  • document.querySelector("span").innerText = 'Disgusting';

     

  • manipulating attributes

         change src and alt text of a img element

  • document.querySelector("img").src = 'https://www.flaticon.com/svg/static/icons/svg/3523/3523063.svg';
    document.querySelector("img").alt = 'chicken';

     

  • changing styles, key word: “.style”, 内容用引号括起来!!!
  • document.querySelector('#container').style.textAlign = 'center';
    
    document.querySelector('img').style.width = '150px';
    
    document.querySelector('img').style.borderRadius = '50%';

     

  • Rainbow Text
  • const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!
    
    //YOU CODE GOES HERE: 7 individual spans, each holds a single letter, 
    const spans = document.querySelectorAll("span");
    //querySelectorAll找出所有的spans
    for(let i = 0; i < 7; i++){ spans[i].style.color = colors[i]; }

    JS-DOM

  • getAttribute/ setAttribute/ .classList/ .classList.add() / .classList.remove() /classList.contains() / classList.toggle()
  • 页面DOM里的每个节点上都有一个classList对象,我们可以新增、删除、修改节点上的CSS类。还可以使用classList判断某个节点是否被赋予了某个CSS类。

  •  以下代码中的border, purple都是写在css里面可以供调用的。 

  • const h2 = document.querySelector("h2");
    
    h2.classList //没有括号,返回所有的class列表
    
    h2.classList.add('border')//属性覆盖,如果已经存在,即更新,不存在,即加上这个属性
    
    h2.classList.add('purple')
    
    h2.classList.remove('border') //去掉这个属性
    
    h2.classList.contains('border') //return true/false

     

  • toggle: 当元素上没有这个CSS类时,它就新增这个CSS类;如果myDiv元素已经有了这个CSS类,它就是删除它。就是反转操作。

JS-DOM

JS-DOM

  • 实现反转效果,js代码里面必须对每一个<li></li>单独操作

 

<!DOCTYPE html>

<head>
    <title>ClasList</title>
    <!--LEAVE THESE LINES ALONE, PLEASE! THEY MAKE THE LIVE PREVIEW WORK!-->
    <script src="node_modules/babel-polyfill/dist/polyfill.js" type="text/javascript"> </script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <link rel="stylesheet" href="app.css">

</head>

<body>
    <!--LEAVE THIS FILE ALONE!-->
    <ul>
        <li>Hello</li>
        <li class="highlight">Hello</li>
        <li>Hello</li>
        <li>Hello</li>
        <li class="highlight">Hello</li>
        <li>Hello</li>
    </ul>
    <script src="app.js"></script>
</body>

</html>
app.css
li { background-color: #B10DC9; } .highlight { background-color: #7FDBFF; }
const lists = document.querySelectorAll("li");

for (let list of lists) {
    list.classList.toggle("highlight")
}
  •  traversing parent/child/sibling
    • .parentElement, 每一个元素都只有一个直系的parent,但是可能会有多个直系的children
      • .parentElement.parentElement.parentElement。可以一层一层往上找到祖宗,曾祖宗
    • .children,返回一个孩子的集合,按照文档的顺序排列的
      • .childrenElementCount计算孩子个数
      • .children[i] 定位到第i个孩子
      • .children[i].parentElement又回到parent 
    • .previousSibing VS .previousElementSibing,nextSibling VS nextElementSibling, 一般使用.ElementSibing可以精准定位到姊妹元素, 而.Sibing很多时候会包含一些空格什么的。

   notes: 定位孩子,姊妹,父亲结点的时候需要先找到一个基准点(通常使用 const base = document.querySelector('#red'); 然后根据这  个base来找其孩子,姊妹,父亲)

  • Append& AppendChild,
    • How to make a new DOM element: .createElemen('tag name'), tag_name = img, div, ...
      • const newImg = document.createElement('img(tag_name)')
    • set attributes for new created element: 根据元素的属性添加对应的属性值
      • newImg.src = "http://zxbnxbcnsbj"
      • newH3.innerText = 'I am a new h3'
      Append it on our page: .appendChild
      • document.body.appendChild(newImg)
    • change the class of the new appended element
      • newImg.classList.add('square'). //css里面设置图片为正方形的属性
    • append VS appendChild
      • append可以同时插入多个不同的结点,可以直接把文字插在后面(append taxt into something directly),例如paragrapg.append('xxxxxx'),内容直接是添加在那个段落的下一句的(inside of the paragraph),而不是另起一个段落
    • prepend, appending before something directly
    • InsertAdjacentElement
      • The insertAdjacentElement() method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.
      • targetElement.insertAdjacentElement(position, element)
      • JS-DOM
      • 还可以直接.after/ .before添加姊妹结点,但是有些浏览器不支持
  • exercie: append 100 buttons inside of div
  • JS-DOM
  • <!DOCTYPE html>
    
    <head>
        <title>100 Buttons!</title>
    </head>
    
    <body>
        <!--DO NOT TOUCH THIS FILE PLEASE!-->
        <h1>Look At All My Buttons!</h1>
        <div id="container">
        
        </div>
    </body>
    
    </html>
    // WRITE YOUR CODE IN HERE:
    const div = document.querySelector('div')
    
    
    for(let i = 0; i < 100; i++){
        const btn = document.createElement('BUTTON')
        btn.innerText = "Hey!"
        div.appendChild(btn);
    }

    思考:为什么 const btn = document.createElement('BUTTON')   btn.innerText = "Hey!"要写在for 循环里面呢?

  • remove/removeChild
    • old version: b.parentElement.removeChild(b) 通过移除父母的孩子来移除当前元素
    • new version: node.remove();
上一篇:正则表达式 ,表单验证(JavaScript)


下一篇:博客园自动点赞代码