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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值