How do I move these elements in DOM

Asked by At

I don't want to change HTML because I want to leave the display the way it is for default view and want to move them in second view. I want to know how I can dynamically order the class of a div.
I want to do this via button click. I have adEventListener() for 'click' where I am doing something and the move logic would go inside this event listener.
I understand that I can get these divs, remove from their parents and place it where I want. But I do not know how to do these for each of them since I have multiple lis. I am struggling with the loop so that I can do these for each li. I need to do this using pure JS and not jQuery.

        <div class="a">
            <div class="b">
                <a class="c">
                    <div class="d"></div>
                    <div class="e">
                        <div class="f"></div> // this is the first item that I want to move
                    <div class="g"></div> // this is the second item that I want to move
            <div class= "h"></div> // I want above mentioned divs to be before this div
//There are multiples lis

2 Answers

Sander Vanden Hautte On

Assuming you would like to do this on load of the page, you could solve your problem with the following JQuery DOM manipulations:

    $("ul .a").each(function(index, element){
    $current_div_a = $(element);

    $div_h = $current_div_a.find(".h");

    $div_f = $current_div_a.find(".f");

    $div_g = $current_div_a.find(".g");

You can test it out on this demo.

I strongly advise against this way of doing it though. I guess it's also the reason why your question got some downvotes too. Just modifying your HTML keeps your code clean, maintainable and clearer for anyone else starting to work on your project. Keeping backwards compatibility for your code as much as possible will cause maintainability problems later.

user7331530 On

I ended up using

var list = document.querySelectorAll("ul li");
                for (var item of list) {
                    let fClass = item.querySelector(".f");
                    let parentOfFirstChildAfterWhichIwantMyF = item.querySelector(//selector for parentOfFirstChildAfterWhichIwantMyF);
                    parentOfFirstChildAfterWhichIwantMyF.insertAdjacentElement("beforeend", fClass);