Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - Changing the order of elements

I am creating a website of floating width. The users use screens from full HD resolution to some 600px on smart phones it seems a pretty good idea. This brings up a very interesting problem.

When user uses a smaller resolution than is an optimum the page gets a lot more height. This means it might be useful to change order of some elements (for example some image, search box or navigation) to make the page more readable without much need of scrooling.

So I need to be able to access DOM and change order of some page elements (swap them).

Lets say I have an list and need to swap item 1 and 2.

<ul>
  <li>1</li>
  <li>2</li>
</ul>

I found a solution based on appending already items elements to <ul> by using function appendChild. However there is a problem with text nodes and it gets really complicated to do it for more difficult element structure, since the need of recreating it whole again.

Do you have any suggestion to improve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For this simple case (swapping the only two elements), you can just use appendChild():

(() => {
  const list = document.querySelector("ul");
  list.appendChild(list.firstElementChild);
})();
<ul>
  <li>List-item #1</li>
  <li>List-item #2</li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...