Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

html - Display content of [object HTMLUListElement] using javascript

I have a javascript function which generates a ul list based on an array being passed in using a similar approach to this - Create a <ul> and fill it based on a passed array

However, when I do the following...

document.getElementById("list").innerHTML = generateListFromArray(array);

All that gets printed is

[object HTMLUListElement]

Can anyone tell me how to print the contents into the div as HTML?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're creating a proper UL element (HTMLUListElement), which is great. You can use that directly by simply appending it to your target:

document.getElementById("list").appendChild(generateListFromArray(array));

If the target already contains content you want to replace (rather than add to), you can clear the target element first:

var list = document.getElementById("list");     // Get the target element
list.innerHTML = "";                            // Remove previous content
list.appendChild(generateListFromArray(array)); // Append your generated UL

There's simply no reason, at all, to convert the element you created to markup first (by using .innerHTML or .outerHTML on the return value of generateListFromArray).

If list is also a ul and you want to replace it, you can do that with insertBefore and removeChild:

var list = document.getElementById("list");     // Get the target element
var parent = list.parentNode;                   // Get its parent
var newList = generateListFromArray(array);     // Get the new one
parent.insertBefore(
    newList,                                    // Insert the new list...
    list                                        // ...before the old one
);
parent.removeChild(list);                       // Remove the old
newList.id = "list";                            // Give the new list the ID the
                                                // old one had

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...