-2
<pre>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</pre>

there are 5 "li" element ,i want to exchange the first "li" element and the last "li" element? just like this:

<pre>
<ul>
<li>5</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>1</li>
</ul>
</pre>
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
cungsong
  • 9
  • 1
  • I don't understand **`change`** in your question. what does it exactly mean? – Divyanshu Sah Sep 17 '21 at 02:32
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 24 '21 at 00:42

2 Answers2

1

Question is similar to this one: Changing the order of elements

Easier if you have unique ids, but it is possible with tag names.

(function() {
  let list = document.querySelectorAll("pre > ul > li")
  list[0].parentNode.insertBefore(list[4], list[0])
  list[0].parentNode.append(list[0]);
})();
<pre>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</pre>
Tom Anderson
  • 942
  • 8
  • 16
0

The naive idea is to get a list of li's, then you pop the first time, then push the same item onto the list, then replace all the children.

Alternatively, Get the content of the first Li, last Li, then replace the values. The first and the second options are semantically different. One copies nodes, while the other merely copies inner text.