添加属性用setAttribute()方法,可以传入两个参数,第一个是属性名称,第二个是要设置的属性值
var li = document.getElementsByTagName('li')[0]//设置 li 属性,如 data-falg,设置为true
li.setAttribute("data-falg", "true")
也可以获取属性用getAttribute(),传入一个参数,是想获取的属性名称,返回的是该属性的值
用setAttribute方法就可以了,如:document.getElementById('d','123456')如果是动态添加标签的话:
var parent = document.getElementById(obj)//添加 div
var div = document.createElement("div")
//设置 div 属性,如 id
div.setAttribute("id", "newDiv")
div.innerHTML = "js 动态添加div"
parent.appendChild(div)
两个insert方法返回的就是被插入的对象,直接操作这两个对象就行了。
var tr = table.insertRow()var td = tr.insertCell()tr.setAttribute('align','center') '不用setAttribute而直接使用属性也可以.tr.setAttribute('bgcolor','#FF0000')
td.width=100 直接对属性赋值的作法。
要在tr元素的父元素中才能增加行,不能在tr本身去增加行。而tbody就是tr的父元素。如果是增加td,就要用tr,因为tr是td的父元素。
<script>// Last updated 2006-02-21 function addRowToTable() { var tbl = document.getElementById('tblSample')var lastRow = tbl.rows.length。
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow。
var row = tbl.insertRow(lastRow)// left cell var cellLeft = row.insertCell(0)var textNode = document.createTextNode(iteration)cellLeft.appendChild(textNode)
// right cell var cellRight = row.insertCell。
var el = document.createElement('input')el.type = 'text'el.name = 'txtRow' + iterationel.id = 'txtRow' + iterationel.size = 40。
el.onkeypress = keyPressTestcellRight.appendChild(el)。