为了转生而点技能-JavaScript,day25(DOM介绍

DOM:document object model。

定义:网页就是一个document,可以利用chrome的开发者工具观察到,各种标签都是element
https://ithelp.ithome.com.tw/upload/images/20211221/20143762S2GZzlFW05.jpg

document.querySelector('.选择器或是标签'):当我们在.js档中,填入本行程序码,并输入想编辑的选择器或是标签,就可以利用;如果有多个相同的标签,则只会选取第一个

let el = document.querySelector('.navbar');

https://ithelp.ithome.com.tw/upload/images/20211221/201437627HkVmusBsG.jpg

document.querySelectorAll('.选择器或是标签'):可以同时选取多个相同的标签,并以阵列型态呈现;如想利用API进行编辑需用阵列方式如,el[0]进行。
https://ithelp.ithome.com.tw/upload/images/20211221/20143762lo54BtHLYe.jpg


简单应用

element.textContent:变更目标选择器或是标签的文字内容

let el = document.querySelector('.选择器或是标签');
el.textContent = 'CCC';      //变更目标选择器或是标签的文字内容为CCC

element.innerHTML:会先删掉html的预设元素,再新增html标签元素

let el = document.querySelector('.选择器或是标签');
el.innerHTML = '<h1>new标题</h1>';

element.insertAdjacentHTML(position, text);:在4个可以自行选择的位置中,插入想要的标签及内容

<!-- beforebegin -->      //位置1
<p>
  <!-- afterbegin -->     //位置2
  foo
  <!-- beforeend -->      //位置3
</p>
<!-- afterend -->         //位置4
let el = document.querySelector('.选择器或是标签');
el.insertAdjacentHTML('beforebegin', '<h1>new标题</h1>');;

element.setAttribute(name, value);:name为属性名称,value为属性值;可以针对目标标签的属性作编辑。

let el = document.querySelector("table");
console.log(el);

https://ithelp.ithome.com.tw/upload/images/20211221/20143762mavg0g5bX3.jpg

let el = document.querySelector("table");
console.log(el);
el.setAttribute("class", "red");

https://ithelp.ithome.com.tw/upload/images/20211221/20143762rEkPR5pBRZ.jpg


element.getAttribute(name, value);:可以用获取标签的内部属性之值,例如classherf

let el = document.querySelector("th");
console.log(el);

https://ithelp.ithome.com.tw/upload/images/20211221/20143762njzMm0Sxjr.jpg

console.log(el.getAttribute("class"));     //red
console.log(el.innerHTML);                 //<span>内容</span>
console.log(el.textContent);               //内容

表单取值

//html
<input type="text" class="txt" value="E-mail">



//.js
let el = document.querySelector(".txt");
console.log(el);

console.log(el.value);   
el.value = '联络资讯';   //赋予新的值
console.log(el.value);

https://ithelp.ithome.com.tw/upload/images/20211221/20143762RJfTll68Xl.jpg


反查document.querySelector作用在DOM的节点位置:

有时因为需要,所以查询作用的节点位置(标签),此时可以利用nodeName

let el = document.querySelector(".button");
console.log(el.nodeName);   //INPUT

<<:  map结构的遍历

>>:  19.MYSQL NOT指令

Azure Database for MySQL 手把手基础教学

葛瑞部落格欢迎光顾 Azure Database for MySQL 前置作业 一组有效的Azure...

[Day7] Android - Kotlin笔记:JetPack - KTX简介

KTX是Jetpack中的一套extension, 提供了许多简洁、惯用的 Kotlin用法。 写法...

Day7 - 条件,重复,回圈与互动- 回圈的设定

利用生活中不同我们很多时候会看到重复性的曲线来去展现出美术, 来让自己有不同的设定跟展现 重复後给定...

D10 第五周 (回忆篇)

这周原则上是复习周,没有太多课程进度,然後老师有提供一个线上挑战游戏,顺便让大家可以复习 API 相...

问题整理(一)Day5

这边把之前遇到的几个问题做一个问题整理 Computed Property Get and Set ...