简体   繁体   中英

How can do simple DOM -manipulation in UL-LI -block with Javascript?

We have had quite long chat here with rlemon about DOM manipulation. Basically the question is 'How can I change the UL-LI DOM with Javascript?' For example, suppose I want, instead of "<ul id='uids'><li>1</li><li>2</li></ul>" , to display something like this "<ul><li><i>Hello 1, have a nice day!</i></li>...</ul>" -- how can I do that just with DOM -manipulation?

I know this is simple question so instead of reinventing-the-wheel, I am happy with references.

Simple demo about DOM manipulation, can you do something like this?

Input

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

Output

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

Perhaps useful for other newbies to get familiar with functional nature of JS

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

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

The short way, using 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/

The long way, with true DOM manipulation:

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/

One approach is as follows:

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 .

References:

Here's another approach:

http://jsfiddle.net/cWRPZ/

starting with:

<ul>
    <li>1</li>
    <li>2</li>
</ul>

and the js is..

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();

Some important things to remember, there are a few nodeTypes in the DOM, and not all of them will be what you are after, so you should be filtering. If there was a comment node, for example, in front of the text then this wouldn't work as you expect.

"Unlearning Is Pretty Hard."

I am analyzing their codes with a tool JSLint here introduced in the video about 44.00 point here . Brilliand's simple version has the smallest amount of spec(?) mistakes. Video mentions that something called ES3.1 is coming, anyway I am not qualified to say whether they are now right-or-wrong -- depends on the specs (the current one from 1999 according to the video). Anyway, I am inclined to use the simple -method, feedback about the analysis?

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

Simple

 '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 
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 my take one it, however as it stands if possible do this all on the server before you output the list to the document... makes much more sense that way.

Here is a DEMO with a little spin on message generation ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM