Interacting with browser

We can get an element reference from the DOM,so that we can interacte with the page.

在这里插入图片描述
document is created by the browser

在这里插入图片描述

get element reference

jsfiddle querySelector practice 最常见的两种从documentt中获取element 的方式。

  1. querySelector return the first element that satisfy the condition.
  2. querySelectorAll return NodeList.

另外还有其他三个方法 jsfiddle Id,class,tagName

// selet the first element
const para = document.querySelector('p.error')

// select all p elements and return NodeList
const paras = document.querySelectorAll('p')

// get an element By ID
const title = document.getElementById("page-title");

// get elements by class and return HTMLCollection
const pEls = document.getElementsByClassName("error")

// get elements by tag name and return HTMLCollection
const pTags = document.getElementsByTagName('p')

Adding & changing page content

jsfiddle add & changing page content demo

  1. innerText
  2. innerHTML

get & set attribute

jsfiddle get & set attribute lab

  1. getAttribute('attribute name')
  2. setAttribute('attribute name','attribute value')

change css style

jsfiddle: change css style
元素有style属性

let title = document.querySelector('h1');
title.style.fontSize="12px";

add & remove class

jsfiddle: add & remove class元素有classList属性

let p = document.querySelector('p');
// remove class
p.classList.remove('error');
// add class
p.classList.add('success');
// add or remove class by class
p.classList.toggle('success');
p.classList.toggle('success');

一个小练习:将内容中含有success或error使用相应的success ,error class.
在这里插入图片描述
jsfiddle: add class accord to content

注意使用textContent,而不是innerText,她们的区别在于:
在这里插入图片描述

let p = document.querySelector('p')
console.log(p.innerText) // 不会显示隐藏的内容
console.log(p.textContent) // 会显示隐藏的内容

parent & children & sibling

jsfiddle: parent & children & sibling

let article = document.querySelector('article');
let title = document.querySelector('h2')
// all children 直接孩子
console.log(Array.from(article.children))
// parent
console.log(title.parentElement)
// 下一个兄弟节点
console.log(title.nextElementSibling)
// 上一个兄弟节点
console.log(title.previousElementSibling)

Event Basic

add an event

为元素添加事件addEventListener,浏览器传递进来的event属性,event.target代表当前元素,我们可以捕获他
jsfiddle: add event
在这里插入图片描述

remove & add element

在DOM中添加和删除元素

// 在末尾添加
ul.append(li);
// 在头部添加
ul.prepend(li);
// 删除
li.remove();

event bubbling(冒泡)

阻止事件冒泡: 如在todos中只能删除新添加的选项,而原来固定的选项不能删除,也就说固定选项li有自己事件监听,而在总的ul也有一个事件监听,而在原本的li中阻断了事件冒泡。
jsfiddle: event bubbling

// 阻止事件冒泡
e.stopPropagation();

Edit by Ipad

发布了121 篇原创文章 · 获赞 3 · 访问量 4174

猜你喜欢

转载自blog.csdn.net/Q10CAU/article/details/104850596