js中对节点属性的操作和对节点的操作

时间:2023-12-04 20:38:26

常用的节点属性操作方法

1.setAttribute(name,value):给某个节点添加一个属性

2.getAttribute(name):获取某个节点属性的值。

3.removeAttribute(name):删除某个节点的属性。

例:

    window.onload = function(){
        //查找body节点
        var node_body = document.body;
        //alert(node_body);
        //查找img节点
        var imgObj = node_body.firstChild;
        //增加src属性
        imgObj.setAttribute("src","./img/1.jpg");
        imgObj.setAttribute("width","200");
        imgObj.setAttribute("border","2");
        imgObj.setAttribute("style","cursor:pointer");
        //删除属性
        imgObj.removeAttribute("border");
   }

对节点的操作

//节点的创建
  //createElement(tagName):创建一个指定的HTML标记

tagName:是指不带尖括号的HTML标记名称

例:var imgObj = document.createElement();
  //appendChild(elementObj):将创建的节点,追加到某个父节点下

        elementObj是创建的一个子节点

        例:document.body.appendChild(imgObj)
  //removeChile(elementObj):删除子节点

//网页加载完成后

例:
  window.onload = function(){
            //创建一个<img>标记
            var imgObj = document.createElement("img");
           //增加属性
           imgObj.setAttribute("src","./img/1.jpg");
           imgObj.setAttribute("width","700");
           //将创建的图片节点
           document.body.appendChild(imgObj);

}