Use jQuery/Javascript to create a list of all elements in a set

拈花ヽ惹草 提交于 2019-12-11 07:45:37

问题


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?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4378602/use-jquery-javascript-to-create-a-list-of-all-elements-in-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!