Deploying ul in li please pure js :)

how to deploy ul in li?

it is like this:

<div id="Australian-Brother" >
<li>1</li>
<li>2</li>
<li>3</li>
</div>

I want to leave it like this:

<div id="Australian-Brother" >
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>

Please post the code most responsible for producing the current “is like this” HTML With luck it could be a line or two tweak.

3 Likes

Could it be that he wants JavaScript that will transform the first HTML example into the second set of HTML?

1 Like

Probably he wanted to say where ul is missing how to envelop all li tags in one common ul.

Teh codez:

const container = document.getElementById('Australian-Brother');
const lis = container.querySelectorAll('li');
const ul = document.createElement('ul');
lis.forEach((li) => { ul.appendChild(li); });
container.innerHTML = '';
container.appendChild(ul);

Is there a more concise way to do it?

1 Like

In this case it may already be to late as the browser tried to fix the invalid markup by itself, leading to a hardly predictable element tree (especially if you have nested lists). One might get away with a simple markup as in the OP though.

Well you don’t need to clear the container HTML as appendChild() doesn’t clone but move the child node… and using append() instead you could just nicely spread the container children:

const container = document.getElementById('Australian-Brother')
const list = document.createElement('ul')

list.append(...container.children)
container.append(list)

But again I think this is purely academic – better use valid markup from the start. ^^

2 Likes

Absolutely. As you say, an academic exercise.

Lol, oh yeah.

Much more concise. Nice one.

I know we don’t need it nowadays, but I still miss jQuery:

$('#Australian-Brother').append('<ul>');
$('ul').append($.find('li'));
1 Like
$('#Australian-Brother > li').wrapAll('<ul />')

Booya! :-D

2 Likes

Lol, beaten. You 'da man!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.