1

I have several Objects that contain a reference to DOM elements:

var liObjs = [new Li($el1, price), new Li($el2, price), new Li($el3, price)]

// Li Model
function Li($element, price){
 var self = this;

 self.price = price; 
 self.$element = $element;
}

// My DOM Looks like this:
<ul>
 <li>Price: $3</li>
 <li>Price: $1</li>
 <li>Price: $2</li>
</ul>

And and I need them sorted by price based on the objects in liObjs.

I've managed to sort liObjs based on each objects price property but I cannot render them in order for the life of me. Please help.

Note: The <li>s are already created in DOM but I need to reorder them when the page loads.

1
  • 1
    There's no jQuery code here. Is $el1 a DOM element or the jQuery object containing it. Commented Mar 15, 2017 at 19:36

1 Answer 1

2

Non jQuery Way

// Remove existing elements from the parent node.
var parent = liObjs[0].$element.parentNode;

while (parent.hasChildNodes()) {
  parent.removeChild(parent.lastChild);
}

// Assuming you have already sorted the array
// you can simply loop through them and add them

liObjs.forEach(function(item) {
  parent.appendChild(item.$element);
});

jQuery Way

$(liObjs[0].$element)
  .parent()
  .empty()
  .append(liObjs.map(function(item) {
    return item.$element;
  }));

Here's a CodePen showing how this works.
http://codepen.io/jessegavin/pen/NpavgZ?editors=1010

Sign up to request clarification or add additional context in comments.

3 Comments

wouldn't parent.html(''); be faster?
I am pretty sure parent.html(''); destroys the li nodes. If you call .removeChild() they remain in memory which is nice because you maintain a reference to them in your liObjs array. Also... I doubt you'll notice any difference in performance.
@jessegavin I don't think so. As long as you have references to them, the nodes still exist, they just get detacthed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.