fandiahm
fandiahm

Reputation: 113

Javascript dom manipulation by data object

I have HTML like this

<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

I want to convert it become like this

<div class="fruits">
<p id="pid_0" data-show="wid_0">
    <span id="wid_0" data-price="100" data-code="1">Banana</span>
    <span id="wid_1" data-price="200" data-code="2">Apple</span>
    <span id="wid_2" data-price="300" data-code="3">Orange</span>
    <span id="wid_3" data-price="400" data-code="4">Melon</span>
    <span id="wid_4" data-price="500" data-code="5">Papaya</span>
</p>
<p id="pid_5" data-show="wid_5">
    <span id="wid_5" data-price="600" data-code="6">Avocado</span>
    <span id="wid_6" data-price="700" data-code="7">Coconut</span>
    <span id="wid_7" data-price="800" data-code="8">Strawberry</span>
</p>

This is how I got so far

<script>
var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

$(".fruits").each(function() { 
    $(this).text($(this).text().replace(/\w+/g, "<span>$&</span>")); 
    $(this).text($(this).text().replace(/\[/g, "<p> ")); 
    $(this).text($(this).text().replace(/\]/g, "</p>")); 
});

var str = $(".fruits").text();
var words = str.split(" ");
var result = [];
var obj = {};

for (var i = 0; i < words.length - 1; i++) {
    // words
    words[i] += " ";

    var w = "wid_"+i;
    var p = "pid_"+i;

    var price = price_arr[i];
    var code = code_arr[i];
    var name = words[i] += " ";

    obj = {get_price:price, get_code:code, display:name};
    result.push(obj);
}
</script>

I'm want to use data object(obj) and store it to each html attribute, but I'm getting stuck. Anyone please help me, I will be highly appreciate.

Upvotes: 1

Views: 89

Answers (2)

guest271314
guest271314

Reputation: 1

You can parse the .textContent of .fruits element to create an array using .replace(), JSON.parse(); use $.map() to create html from array elements, set .innerHTML of .fruits using .html().

Increment variables storing 0, 0, 1, 0 for id of p elements, id of span elements, "code" and "price" data-* attributes set with data at jQuery(html, attributes)

var fruit = $(".fruits");
var data = fruit.text()
           .replace(/(\w+)/g, "\"$1\",")
           .replace(/,(?=\s])/g, "")
           .replace(/\]\[/, "],[");
var id = 0;
var s = 0;
var w = 1;
var n = 0;

var html = $.map(JSON.parse("[" + data + "]"), function(el) {
  var p = $("<p>", {
            id: "pid_" + id,
            html: $.map(el, function(_fruit) {
                    return $("<span>", {
                             id:"wid_"+ (s++),
                             text: _fruit + "\n"
                           })
                           .attr({
                             "data-price": (n += 100),
                             "data-code": w++
                           })
          })
  }).attr("data-show", "wid_" + id);

  id += 5;
  return p;
});

fruit.html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

Upvotes: 1

prasanth
prasanth

Reputation: 22500

Simply use with Array#map function append() function of jquery

  1. first separate the html data in to two array
  2. Then map with each array.
  3. Finally map with each array with in arguments.
  4. Then append with in a fruits

var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

var a = $('.fruits').text().split('][')
$('.fruits').empty()
var k = 0;
var c = 0;
var result = []
var res = [];
a.map((a, b) => {
  $('.fruits').append('<p id="pid_' + k + '" data-show="wid_' + k + '"></p>')
  a.replace(/\]|\[/g, "").split(" ").map((a, b) => {
    if (a) {
      result[c] = {
        get_price: price_arr[c],
        get_code: code_arr[c],
        display: a,
      };
      $('#pid_' + k + '').append('<span id="wid_' + c + '" data-price="' + price_arr[c] + '" data-code="' + code_arr[c] + '">' + a + '</span>')
      c++;
    }
  })
  k = c
})
console.log(result);
console.log($('.fruits').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

Upvotes: 1

Related Questions