Denis
Denis

Reputation: 73

Find and get id attributes inside of html and replace it - jQuery

i try using this question here for serialized the attributes but not working on different case, how to find the whole attribute inside the .main div parent

$(".send").click(function() {

  var data_array = new Array();
  $(".main").each(function() {
    var item = {};
    for (var i in $(this).attr('id')) {
      item[i] = $(this).attr(i);
    }
    data_array.push(item);

  });
  var serialized = JSON.stringify(data_array);

  $("#result").text(serialized);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="main">
  <ul>
    <li class="dropped" data-order="0" data-id="1" data-content="blabla" id="first">first</li>
    <li class="dropped" data-order="0" data-id="2" data-content="another content" id="second">second</li>
  </ul>
<labe for="input1">Name: </labe>
<input type="text" id="input1" />
</div>

<div id="result"></div>

<button class="send">Send</button>

i'm trying to get all of ID inside the <div class="main"> including input, label, and also tag <li>

Upvotes: 0

Views: 225

Answers (1)

Always Helping
Always Helping

Reputation: 14570

You need to use Descendant Selector in your case to get all the data-attributes for your .main class. Simply using .main on $.each will not work in your case.

Edit: As per the conversation you want find the id in the .main html class and replace the existing id's with some new one. Its all working now you can click send and old id's will be stored in an array and new id's will be applied the HTML elements.

Demo:

$(".send").click(function() {
  var data_array = []
  $(".main").each(function(index, el) {
    //store object
    var item = {};
    //find all the li in .main
    $($(el).find('li')).each(function(ind, li) {
      item["id" + ind] = $(li).attr('id') //store old li id
      $(li).attr("id", "new-li" + ind); //li change new id
    })
    //store input id
    item['id'] = $(el).find('input').attr('id') //store old id
    $(el).find('input').attr('id', 'new-input-id') //assign input new id
    //Push old id's data to array
    alert('All id`s replaced for li and input')
    data_array.push(item);
  });
  console.log(data_array)
  var serialized = JSON.stringify(data_array);
  $("#result").text(serialized);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="main">
  <ul>
    <li class="dropped" data-order="0" data-id="1" data-content="blabla" id="first">first</li>
    <li class="dropped" data-order="0" data-id="2" data-content="another content" id="second">second</li>
  </ul>
  <labe for="input1">Name: </labe>
  <input type="text" id="input1" />
</div>

<div id="result"></div>

<button class="send">Send</button>

Upvotes: 2

Related Questions