JavaScript给HTML标签插入一个属性(或者更换一个id值)(JavaScript inserts an attribute (or replaces an ID value) into the HTML tag)

本次实验的目的是更换html的body的id值,不管body标签有没有id都可以。

js代码:

    var body = document.getElementsByTagName("body")[0];    var att = document.createAttribute("id");    att.value = "qsdf";    body.setAttributeNode(att);
  • var body = document.getElementsByTagName(“body”)[0];
  • var att = document.createAttribute(“id”);
  • att.value = “qsdf”;
  • body.setAttributeNode(att);

第一行代码是    var body = document.getElementsByTagName(“body”)[0];

是找到body标签,

第二行代码是    var att = document.createAttribute(“id”);

创建你要添加的属性,这里以id为例;

第三行代码是: att.value = “qsdf”;

给创建的属性赋值

第四行代码是:body.setAttributeNode(att);

把创建好的属性添加到指定的标签位置。

————————

The purpose of this experiment is to change the ID value of HTML body, no matter whether the body tag has ID or not.

JS code:

    var body = document.getElementsByTagName("body")[0];    var att = document.createAttribute("id");    att.value = "qsdf";    body.setAttributeNode(att);
  • var body = document.getElementsByTagName(“body”)[0];
  • var att = document.createAttribute(“id”);
  • att.value = “qsdf”;
  • body.setAttributeNode(att);

The first line of code is      var   body  =  document.getElementsByTagName(“body”)[0];

Is to find the body tag,

The second line of code is     var   att  =  document.createAttribute(“id”);

Create the attribute you want to add. Here, take id as an example;

The third line of code is:   att.value  =  “qsdf”;

Assign a value to the created property

The fourth line of code is: body. Setattributenode (attribute);

Add the created attribute to the specified label position.