• DEVHIDE
          • Home (current)
          • About
          • Contact
          • Cookie
          • Home (current)
          • About
          • Contact
          • Cookie
          • Disclaimer
          • Privacy
          • TOS
          Login Or Sign up

          How to append li element, to another list

          58 Views Asked by Christian Ansel Thrige At 02 February 2024 at 10:35 2025-11-26T04:40:52.902000

          I have a list that i want to append another list on certain conditions.

          The structure looks like this:

          <ul class="menu">
          <li class="list-1"><ul class="ul-1"></ul></li>
          <li class="list-2"><ul class="ul-2"></ul></li>
          <li class="list-3"><ul class="ul-3"></ul></li>
          <li class="list-4 empty-list"></li>
          <li class="list-5"><ul class="ul-5"></ul></li>
          </ul>
          

          I want the list-4 empty-list, to be inside the list before it. So in this case,inside list-3, if the list is empty. I have made a check to check if lists are empty, thats why the list-4 has a class callled empty-list.

          Can it be done with javascript? I have had trouble researching to a solution, also because i an not 100% sure how to describe it.

          Thanks

          I tried something like this:

          document.addEventListener('DOMContentLoaded', function () {
              var listItems = document.querySelectorAll('.list');
          
              listItems.forEach(function (listItem, index) {
                var nextSibling = listItem.nextElementSibling;
          
                if (nextSibling && nextSibling.classList.contains('list-')) {
                  var emptyList = listItem.querySelector('.empty-list');
          
                  if (emptyList) {
                    nextSibling.appendChild(emptyList);
                  }
                }
              });
            });
          

          I am still new to this sort of coding, so tried my best.

          javascript list append unordered
          Original Q&A
          2

          There are 2 best solutions below

          0
          T.J. Crowder T.J. Crowder On 02 February 2024 at 10:48

          To do what you describe, you can:

          1. Find the .empty-list li element. document.querySelector can do that for you.
          2. Get the li in front of it, and then find the first ul inside it. previousElementSibling is good for getting the previous li (since there can't be anything else in a ul), and the element-specific version of querySelector is useful for finding the first ul within it.
          3. See if that's empty via .children.length === 0.
          4. If so, move the .empty-list element into it via appendChild as you have in your question (or append).

          Here's an example:

          // Find the `.empty-list` element
          const emptyListItem = document.querySelector(".empty-list");
          // Get the `li` previous to it, and find the (first) `ul` within that `li`
          const previousList = emptyListItem
              .previousElementSibling
              .querySelector("ul");
          // If that `ul` has no element children, move the empty `li` into it
          if (previousList.children.length === 0) {
              previousList.appendChild(emptyListItem);
          }
          
          // (Just to show the resulting structure)
          console.log(document.querySelector(".menu").outerHTML);
          <ul class="menu">
          <li class="list-1"><ul class="ul-1"></ul></li>
          <li class="list-2"><ul class="ul-2"></ul></li>
          <li class="list-3"><ul class="ul-3"></ul></li>
          <li class="list-4 empty-list"></li>
          <li class="list-5"><ul class="ul-5"></ul></li>
          </ul>

          0
          Mehdi Mehdi On 02 February 2024 at 14:27

          You can also check this code. First check which li has no children with listItem.childNodes.length===0 get its class (using className) and select it (using getElementsByClassName) then get the previous element with same approach. In this case I first check if your 'orphan' li is not the first element in case your li order changes with (index!=0). In case order changes and orphan 'li' is the first element you will

          document.addEventListener('DOMContentLoaded', function () {
              var listItems = document.querySelectorAll('li');
              const menu = document.querySelector('.menu')
              listItems.forEach(function (listItem, index) {
                if (listItem.childNodes.length===0) {
                      let className = listItem.className
                      let elemToInsert = Array.from(document.getElementsByClassName(className))
                      elemToInsert[0].remove()
                      if(index!=0){
                          let PrevElem = listItems[index-1].children
                          className = PrevElem[0].className
                          let elemToInsertIn = Array.from(document.getElementsByClassName(className))
                          elemToInsertIn[0].appendChild(elemToInsert[0])
                      }
                      else if(index ===0){
                          // let PrevElem = listItems[selectedIndex].children // you need to set selectedIndex
                          // className = PrevElem[0].className
                          // let elemToInsertIn = Array.from(document.getElementsByClassName(className))
                          // elemToInsertIn[0].appendChild(elemToInsert[0])
                      }
                }
              });
              console.log(menu)
            });
          <ul class="menu">
                  <li class="list-1">
                      <ul class="ul-1"></ul>
                  </li>
                  <li class="list-2">
                      <ul class="ul-2"></ul>
                  </li>
                  <li class="list-3">
                      <ul class="ul-3"></ul>
                  </li>
                  <li class="list-4 empty-list"></li>
                  <li class="list-5">
                      <ul class="ul-5"></ul>
                  </li>
              </ul>

          have to select the index of the element to insert in

          Related Questions in JAVASCRIPT

          • Using Puppeteer to scrape a public API only when the data changes
          • inline SVG text (js)
          • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
          • Storing the preferred font-size in localStorage
          • Simple movie API request not showing up in the console log
          • Authenticate Flask rest API
          • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
          • How to request administrator rights?
          • mp4 embedded videos within github pages website not loading
          • Scrimba tutorial was working, suddenly stopped even trying the default
          • In Datatables, start value resets to 0, when column sorting
          • How do I link two models in mongoose?
          • parameter values only being sent to certain columns in google sheet?
          • Run main several times of wasm in browser
          • Variable inside a Variable, not updating

          Related Questions in LIST

          • How to give the player the ability to choose a grid in Battleship?
          • Sorting a List by its property renames all the objects in the List
          • Replace NA in list of dfs in certain columns and under certain conditions
          • Why does print(list.sort()) result in None?
          • How to distribute the sum of several numbers similarly?
          • Random getting value from a range or a specific value
          • drop down list to decide which range my graph will plot
          • List > numpy.ndarray using np.array(list) not working in class __init__ . Problem with numpy?
          • Creating an efficent and time-saving algorithm to find difference between greater than and lesser than combination
          • Flutter: How to add items and save it in local storage?
          • Why my code is working on everything except one instance?
          • Why does the following code detect this matrix as a non-singular matrix?
          • How do I convert a list of chars into a list of strings in F#?
          • Going back to an earlier index in list iteration
          • If the element(s) in the first list equal element(s) of the second list, replace with element(s) of the third list

          Related Questions in APPEND

          • Power Query / M Code, extract a list of tables into one main table, some column headers same but some different and in different order (and in row 2)
          • List append dictionary - handling missing data
          • How to append an array vector to a database?
          • VBA find matching Excel files with a subtext - and merge them into single new file
          • Add a blank row to an R dataframe if a condition is met eleswhere in the dataframe
          • Concatenate data frames in R
          • jsonata expression to append the value
          • Appending vector creating two separate lists in R
          • Append DF with different lengths Python
          • Power BI: How to add custom column when "append queries as new table"
          • Appending nested dictionary objects to a list based on the values of the nested dictionary object. PYTHON
          • Updating selective columns in and appending new rows to Historical Table from Update Table
          • Append to same file from different processes concurrently on MacOS
          • My php code seems fine but there are two similar functions where one fails and other runs successfuly
          • How do I append an input element with an attribute of checkbox?

          Related Questions in UNORDERED

          • How to append li element, to another list
          • How to handle unordered sets of tags in Python Pandas Dataframe in terms of merging
          • Python: How to get the unordered result from starmap_async
          • jQuery versions after 3.3.1 are corrupting html inserted in a page with .html()
          • Erase element from unordered_set of shared pointer
          • How can I tell R to use a specific reference level in a linear model?
          • Angular shows random image order but it should't
          • why parallel streams will only perform a concurrent reduction if either (not both) the stream is unordered, or the collector is UNORDERED?
          • Django Password not encrypted, custom user model using (AbstractUser)
          • C# Dictionary that uses an Unordered Pair as its Key?
          • Sort strings of ints and save original index
          • SQL Server Insert on the last Row
          • Cloud Pub/Sub - Single message delaying others (HoL blocking?)
          • Why does an unordered sequential stream always return the same thing to me when it shouldn't?
          • Matching unordered values in R

          Trending Questions

          • UIImageView Frame Doesn't Reflect Constraints
          • Is it possible to use adb commands to click on a view by finding its ID?
          • How to create a new web character symbol recognizable by html/javascript?
          • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
          • Heap Gives Page Fault
          • Connect ffmpeg to Visual Studio 2008
          • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
          • How to avoid default initialization of objects in std::vector?
          • second argument of the command line arguments in a format other than char** argv or char* argv[]
          • How to improve efficiency of algorithm which generates next lexicographic permutation?
          • Navigating to the another actvity app getting crash in android
          • How to read the particular message format in android and store in sqlite database?
          • Resetting inventory status after order is cancelled
          • Efficiently compute powers of X in SSE/AVX
          • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

          Popular # Hahtags

          javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

          Popular Questions

          • How do I undo the most recent local commits in Git?
          • How can I remove a specific item from an array in JavaScript?
          • How do I delete a Git branch locally and remotely?
          • Find all files containing a specific text (string) on Linux?
          • How do I revert a Git repository to a previous commit?
          • How do I create an HTML button that acts like a link?
          • How do I check out a remote Git branch?
          • How do I force "git pull" to overwrite local files?
          • How do I list all files of a directory?
          • How to check whether a string contains a substring in JavaScript?
          • How do I redirect to another webpage?
          • How can I iterate over rows in a Pandas DataFrame?
          • How do I convert a String to an int in Java?
          • Does Python have a string 'contains' substring method?
          • How do I check if a string contains a specific word?
          .

          Copyright © 2021 Jogjafile Inc.

          • Disclaimer
          • Privacy
          • TOS
          • Homegardensmart
          • Math
          • Aftereffectstemplates