abms
abms

Reputation: 575

How to order html elements in the same order as array using jQuery?

I'd like to order html elements in the same order as arrayData.

JavaScript

    var arrayData = [59, 56, 57];

HTML

    <div class="selectize-input">
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
        <div class="item" data-value="59">Cat</div>
    </div>

I want the result like this.

    <div class="selectize-input">
        <div class="item" data-value="59">Cat</div>
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
    </div>

Is there any good way to achive this? Thank you in advance.

[Additional] I want to get result something like this, but don't now how to apply it to html elements and render on browser.

const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);

Upvotes: 1

Views: 74

Answers (3)

Aditya Dwivedi
Aditya Dwivedi

Reputation: 11

  1. If you only have the parent element in html and want to add the child div in sorted order then :

    const divList = [ {value:59, title:"Cat"}, {value:56, title:"Dog"} ]

      divList.forEach((obj) => {
    
        $("<div />")
            .html(obj.title)
            .attr('data-value', obj.value)
            .addClass('item')
            .appendTo( $('.selectize-input'))
    

    })

Codepen : https://codepen.io/AdityaDwivedi/pen/pojMYRr

  1. If you already have the div element added in your html & you want to sort them up :

    <div class="selectize-input"> <div class="item" data-value="56" id="56">Dog</div> <div class="item" data-value="57" id="57">Rabbit</div> <div class="item" data-value="59" id="59">Cat</div> </div>

`

const divOrder = ["59", "56", "57"]
    const orderedDiv = $('.selectize-input > div').sort((a, b) =>
    divOrder.indexOf(a.id) - divOrder.indexOf(b.id)
    ); 



  $('.selectize-input').empty()

orderedDiv.map((obj) =>{
  $("<div />")
            .html(orderedDiv[obj].innerHTML)
            .attr('data-value', orderedDiv[obj].value)
            .appendTo( $('.selectize-input'))})

`

Codepen : https://codepen.io/AdityaDwivedi/pen/QWjeopv?editors=1111

Upvotes: 1

Swati
Swati

Reputation: 28522

You can loop over your array using $.each and then use append to add div at particular position.

Here is demo code :

var arrayData = [59, 56, 57];
//looping through array
$.each(arrayData, function() {
//append div at particular positon using data-value
  $(".selectize-input").append($("div [data-value=" + this + "]"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selectize-input">
  <div class="item" data-value="56">Dog</div>
  <div class="item" data-value="57">Rabbit</div>
  <div class="item" data-value="59">Cat</div>
</div>

Upvotes: 1

Cal Courtney
Cal Courtney

Reputation: 1289

So, I'm not quite sure if I fully understand the question. But if you're trying to dynamically render a div for each piece of data, you could try something like...

JS:

const arrayData = [
    {value:59, title:"Cat"},
    {value:56, title:"Dog"},
    {...}
]

arrayData.forEach((dataObject) => {
    $('.selectize-input').append(
        document.createElement('div')
            .innerHTML(dataObj.title)
            .attr('data-value', dataObj.value)
            .addClass('item')
    )          
}

I'm not really a jQuery person, so I'm not entirely sure that this will work, but I believe it will send you in the right direction.

First, I am making your array into an array of objects which include both the value of the item, but also the title of the item.

Then, I am using a forEach loop to run through each item and create a new div based on it. It appends these divs to the .selectize-input.

I hope it helps you.

I should say, the stuff that you're doing here is something that ReactJS is really good at. It's like a souped-up javascript that allows you to create and manipulate HTML elements really easily.

Check it out at https://reactjs.org/!

Upvotes: 1

Related Questions