Listing each individual row using jQuery

I would like to know how to create a list from a block of text. Let me explain ..

Here is my html:

<div class="asd">
well
worth
it
</div>

And it should be automatically converted to a list as follows:

<div class="asd">
<ul>
<li>well</li>
<li>worth</li>
<li>it</li>
</ul>
</div>

I hope you understand: -D I have already tried this with various methods, but am not familiar with jQuery element elements yet.

Martti Lane

+3
source share
1 answer

Something like this should do the trick:

$(".asd").each(function() {
    var list = $("<ul>").insertBefore(this);
    var lines = $(this).remove().text().split("\n");
    list.append($.map(lines, function(str) {
        return $("<li>").text(str).get(0);
    })); 
});

You might want to add some kind of check for empty lines.

+4
source

Source: https://habr.com/ru/post/1730569/


All Articles