Use jQuery/Javascript to create a list of all elements in a set
I want to use Javascript to loop through a set of elements, and create a list of labels for each one, so if the set of elements were as follows:
<h1>Title</h1>
<h2>Subheading</h2>
<p>Paragraph of text...</p>
It would give me the following:
<ol>
<li>h1</li>
<li>h2</li>
<li>p</p>
<ol>
Is 开发者_运维知识库it possible for jQuery/Javascript to return an element's type as a string, and if so how would I go about it?
This is far from the cleanest piece of code I've ever done, but it works:
function generateList(rootElement) {
var rootElementItem = $("<li>" + rootElement.get(0).tagName + "</li>");
if (rootElement.children().size() > 0) {
var list = $("<ol />");
rootElement.children().each(function() {
list.append(generateList($(this)));
});
rootElementItem.append(list);
}
return rootElementItem;
}
var listOfElements = generateList($("body"));
$("body").append($("<ol/>").append(listOfElements));
Demo: http://jsfiddle.net/jonathon/JvQKz/
It builds upon the this.tagName
answer that was previously given, but it checks for children also. This way it will build up a hierarchical view of the element given. The method doesn't generate the enclosing <ol/>
tag so that it can just be appended to an existing one.
I hope this simple solution helps: http://jsfiddle.net/neopreneur/n7xJC/
-html-
<h1>Title</h1>
<h2>Subheading</h2>
<p>Paragraph of text...</p>
-js-
$(function(){
$('body *').each(function(){
// append a 'ol' to body in order to output all tag names
if(!$(this).parents('body').find('ol').length){
$('body').append('<ol/>');
}
// output the name of the tag (list item)
$('ol').append('<li>' + this.tagName.toLowerCase() + '</li>');
});
});
This works assuming you have a properly formed HTML document with a body tag.
example
$('<ol />').append(function(index, html){
var ret = $('<span />');
$('body>*').each(function(i, el) {
ret.append( $('<li />').html(this.tagName.toLowerCase()) );
});
return ret.html();
}).appendTo('body');
精彩评论