<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <div> </div> <input type="text" /> <input type="button" value="添加" /> </div> <div> <ul> <li>红烧肉</li> <li>红烧肘子</li> <li>红烧鱼</li> </ul> </div> <script> function addElen(ths) { var aaa = ths.previousElementSibling.value; // alert(aaa) var list_li = document.getElementById("lis"); // alert(list_li) var bbb = "<li>" +aaa+ "</li>"; // alert(bbb) list_li.insertAdjacentHTML("beforeEnd", bbb) } </script> </body> </html>
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <div> </div> <input type="text" /> <input type="button" value="添加" /> </div> <div> <ul> <li>红烧肉</li> <li>红烧肘子</li> <li>红烧鱼</li> </ul> </div> <script> function addElen(ths){ var aaa = ths.previousElementSibling.value; //获取input的值 var list_li = document.getElementById("lis"); //获取ul var tag = document.createElement('li');//创建li tag.innerText = aaa; //赋予tag也就是新的li标签里面的值是输入的input的值 list_li.insertBefore(tag, list_li.children[-1])//根据索引插入需要位置的值 } </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div> <input type="text" /> <input type="button" value="添加" /> </div> <div> <ul> <li>alex</li> <li>eric</li> </ul> </div> <script> function AddElement(ths){ //获取输入的值 var val = ths.previousElementSibling.value; var commentList = document.getElementById('commentList') //第一种形式 var str = "<li>" + val + "</li>" //'beforeBegin'、'afterBegin'\ 'beforeEnd'\'afterEnd' //beforeEnd 内部最后 //beforeBegin 外部上边 //afterBegin 内部贴身 //afterEnd 外部贴身 // commentList.insertAdjacentHTML("beforeEnd", str) //第二种方式,元素的方式 var tag = document.createElement('li'); tag.innerText = val; var temp = document.createElement('a'); temp.innerText = '百度'; temp.href = "http://www.baidu.com"; tag.appendChild(temp); commentList.insertBefore(tag,commentList.children[1]); console.log(commentList.children[1]) } </script> </body> </html>
案例七: