JavaScript总结:添加,删除,移动元素的位置

To manipulate an element, the steps are: (改变网址)

选择一个元素:document.querySelector();

将reference存储在变量中

: let link = document.querySelector(‘a’);

改变属性: link.herf = ’https://some.website.url/’;

                                                                   link.textContent = ‘UCD Website’;

 

querySelectorAll():  一个 NodeList 对象,表示文档中匹配指定 CSS 选择器的所有元素。

    // 获取文档中所有的 <p> 元素 var x = document.querySelectorAll("p");

// 设置第一个 <p> 元素的背景颜色 x[0].style.backgroundColor = "red";

 

getElementsByTagName() 方法可返回带有指定标签名的对象的集合。

var x=document.getElementsByTagName("input");

  alert(x.length);

  下面的代码可以获得文档中的第四个段落:

var myParagragh = document.getElementsByTagName("p")[3];

 

 

document.getElementById():let myVar = document.getElementById(“firstpara”);

 

 

Steps involved in creating new nodes

▪ Select the parent node, using  document.querySelector();

▪ Create a new element using   document.createElement();

▪ Give it some content (say, textContent, value or href or any other property)

▪ Append new element to the parent node using   appendChild()

 

<script>

let firstpara = document.querySelector(‘#firstpara’);

let newheading = document(‘h5’);

newheading.textContent = ‘A new heading’;

firstpara.appendChild(newheading);

</script>

 

改变元素位置

  1. Get the node you want to remove
  2. Get a new parent node
  3. appendChild to the parent

<script>

         Let firstpara = document.querySelector(‘#firstpara’);

         Let section = document.querySelector(‘section’);

         Section.appendChild(firstChild);

</script>

 

删除元素:

  1. find the node
  2. delete itself

let firstpara = document.querySelector(‘#firstpara’);

firstpara.remove();

删除下拉框中的选项:

var parent = document.querySelector('#colorSelect');

parent.remove(parent.selectedIndex);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值