如何用Javascript在UL-LI -block中进行简单的DOM操作?

时间:2012-06-06 21:45:44

标签: javascript dom

我们与rlemon聊聊DOM操作已经很长时间了here。基本上问题是'How can I change the UL-LI DOM with Javascript?'例如,假设我想要而不是"<ul id='uids'><li>1</li><li>2</li></ul>"来显示类似"<ul><li><i>Hello 1, have a nice day!</i></li>...</ul>"的内容 - 我怎么能用DOM操作来做到这一点?

我知道这是一个简单的问题,所以我很高兴参考,而不是重新发明轮子。

  

关于DOM操作的简单演示,你可以做这样的事吗?

     
    

输入

    <ul id="uid">
            <li>1</li>
            <li>2</li>
    </ul>
         

输出

    <ul id="uid">
            <li>Hello beautful lady 1!</li>
            <li>Hej gentleman 2.</li>
    </ul>
  
     

也许对其他新手有用,可以熟悉JS的功能性

     
      
  1. http://chat.stackoverflow.com/rooms/17/conversation/learn-javascript-videos

  2.   
  3. http://ejohn.org/apps/learn/

  4.   

5 个答案:

答案 0 :(得分:4)

简短的方法,使用innerHTML:

var lis = document.getElementById("uid").getElementsByTagName("li");
for(var i = 0; i < lis.length; i++)
    lis[i].innerHTML = "<i>Hello "+lis[i].innerHTML+", have a nice day!</i>";

jsFidlde:http://jsfiddle.net/eZv4D/3/

漫长的道路,真正的DOM操作:

var lis = document.getElementById("uid").getElementsByTagName("li");
for(var i = 0; i < lis.length; i++) { // Loop through all <li> elements
    // Create an <i> element to contain the text
    var el = document.createElement("i");

    // Add the start of the text to the <i>
    el.appendChild(document.createTextNode("Hello "));
    // Add everything in the <li> to the <i> (they are removed from the <li>)
    while(lis[i].firstChild)
        el.appendChild(lis[i].firstChild);
    // Add the end of the text to the <li>
    el.appendChild(document.createTextNode(", have a nice day!"));

    // Add the <i> to the <li>
    lis[i].appendChild(el);
}

jsFiddle:http://jsfiddle.net/eZv4D/2/

答案 1 :(得分:2)

一种方法如下:

var liElems = document.getElementsByTagName('li'),
    strings = ['Hello beautiful lady ','Hej gentlemen '];

for (var i = 0, len = liElems.length; i < len; i++){
    elem = liElems[i].firstChild,
    curText = elem.nodeValue;
    if (i%2 == 0){
        elem.nodeValue = strings[0] + curText;
    }
    else {
        elem.nodeValue = strings[1] + curText;
    }
}

JS Fiddle demo

参考文献:

答案 2 :(得分:1)

这是另一种方法:

http://jsfiddle.net/cWRPZ/

从:

开始
<ul>
    <li>1</li>
    <li>2</li>
</ul>

和js是..

var demo = {
    __elems: false,
    replacement: 'This is element __replaceme__',
    go: function(){
        this.__elems = document.querySelectorAll('li');
        for(var i = 0; i < this.__elems.length; i++){
            elem = this.__elems[i];
            elem.firstChild.nodeValue = this.replacement.replace('__replaceme__',elem.firstChild.nodeValue);
        }                
    }
}

demo.go();

要记住一些重要的事情,DOM中有a few nodeTypes,而且并非所有这些都是你所追求的,所以你应该过滤。如果有一个注释节点,例如,在文本前面,那么这将无法按预期工作。

答案 3 :(得分:1)

  

“忘却非常困难。”

我正在使用视频中介绍的工具JSLint here分析他们的代码,这些工具是关于44.00点here。 Brilliand的简单版本具有最小量的规范(?)错误。视频提到称ES3.1即将到来,无论如何我没有资格说它们现在是对还是错 - 取决于规格(根据视频来自1999年的当前版本)。无论如何,我倾向于使用简单的方法,关于分析的反馈?

  

David Thomas

'document' was used before it was defined.
var liElems = document.getElementsByTagName('li'),
line 2 character 40Missing space between ',' and 'Hej gentlemen '.
    strings = ['Hello beautiful lady ','Hej gentlemen '];
line 4 character 6Move 'var' declarations to the top of the function.
for (var i = 0, len = liElems.length; i < len; i++){
line 4 character 6Stopping. (30% scanned).
     

<强> Brilliand

     
    

<强>简单

'document' was used before it was defined.
var lis = document.getElementById("uid").getElementsByTagName("li");
line 2 character 4Missing space between 'for' and '('.
for(var i = 0; i < lis.length; i++)
line 2 character 5Move 'var' declarations to the top of the function.
for(var i = 0; i < lis.length; i++)
line 2 character 5Stopping. (66% scanned).
         

DOM -version

'document' was used before it was defined.
var lis = document.getElementById("uid").getElementsByTagName("li");
line 2 character 4Missing space between 'for' and '('.
for(var i = 0; i < lis.length; i++) { // Loop through all <li> elements
line 2 character 5Move 'var' declarations to the top of the function.
for(var i = 0; i < lis.length; i++) { // Loop through all <li> elements
line 2 character 5Stopping. (12% scanned).
  
     

<强> danp

Unexpected dangling '_' in '__elems'.
    __elems: false,
line 4 character 17Expected exactly one space between 'function' and '('.
    go: function(){
line 4 character 19Expected exactly one space between ')' and '{'.
    go: function(){
line 4 character 19Missing space between ')' and '{'.
    go: function(){
line 5 character 9Missing 'use strict' statement.
        this.__elems = document.querySelectorAll('li');
line 5 character 14Unexpected dangling '_' in '__elems'.
        this.__elems = document.querySelectorAll('li');
line 5 character 24'document' was used before it was defined.
        this.__elems = document.querySelectorAll('li');
line 6 character 12Missing space between 'for' and '('.
        for(var i = 0; i < this.__elems.length; i++){
line 6 character 13Move 'var' declarations to the top of the function.
        for(var i = 0; i < this.__elems.length; i++){
line 6 character 13Stopping. (46% scanned).
undefined
document 'go' 4
     

<强> rlemon

'document' was used before it was defined.
var list = document.getElementById('uids'), // get the parent ul
line 3 character 45Expected exactly one space between 'function' and '('.
Array.prototype.forEach.call(items, function(item) { // because nodeLists are not arrays we do this for a forEach
line 4 character 5Missing 'use strict' statement.
    var value = item.textContent || item.innerText; // gets the text content cross browser
line 5 character 10Expected exactly one space between 'while' and '('.
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data
line 5 character 32Expected exactly one space between ')' and '{'.
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data
line 5 character 32Missing space between ')' and '{'.
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data
undefined
document 'items' 3
clear

答案 4 :(得分:1)

var list = document.getElementById('uids'), // get the parent ul
    items = list.getElementsByTagName('li'); // get the items as a nodeList
Array.prototype.forEach.call(items, function(item) { // because nodeLists are not arrays we do this for a forEach
    var value = item.textContent || item.innerText; // gets the text content cross browser
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data
        item.removeChild(item.lastChild);
    }
    item.appendChild(document.createTextNode("Wuddup " + value)); // append your new message :P
});

这是我接受它的一个,但是如果可能的话,在将列表输出到文档之前在服务器上执行此操作......这样做会更有意义。

Here is a DEMO在消息生成方面略微旋转;)