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 的方式。
querySelector
return the first element that satisfy the condition.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
innerText
innerHTML
get & set attribute
jsfiddle get & set attribute lab
getAttribute('attribute name')
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