steel
steel

Reputation: 12520

JQuery: create corresponding elements with same custom attrs

Fiddle here: http://jsfiddle.net/yv1vLhd9/

For whatever reasons, suppose I want to replace three dom elements with three others using JQuery, but I want to transfer one or more data attributes from the first elements onto their corresponding replacements.

Given the following HTML:

<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>

And the following CSS:

div {
  width: 100px;
  height: 100px;  
}

div:before {
  content: attr(data-custom);
}

.original {
  border: blue solid 1px;
}

.new {
  border: pink solid 1px;
}

How can I make sure there is a new element with each of the custom data attributes?

For example:

$(document).ready( function(){
  var $originalEl = $('.original')
  var originalData = $originalEl.data('custom')
  var replacement = '<div class="new" data-custom="' + originalData + '"></div>'
  $originalEl.after(replacement).hide()
});

But this creates three new data-custom="dog" attributes.

Upvotes: 0

Views: 42

Answers (3)

War10ck
War10ck

Reputation: 12508

jQuery provides a host of DOM manipulation methods that will help you achieve the desired input. As noted by some of the other answers, you'll need to traverse over the set of matched elements using $.each. In addition, rather than creating new elements from strings, you can use the .clone() method to:

  1. clone the existing element
  2. modify your new element
  3. insert it after the original element
  4. traverse to the original element
  5. and finally hide the original element.

$(function () {
    $('.original').each(function (idx, elem) {
        $(elem)
            .clone()
            .removeClass('original')
            .addClass('new')
            .insertAfter($(elem))
            .prev()
            .hide();
    });
});
div {
  width: 100px;
  height: 100px;  
}

div:before {
  content: attr(data-custom);
}

.original {
  border: blue solid 1px;
}

.new {
  border: pink solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>

API Method References:

Upvotes: 1

Vixed
Vixed

Reputation: 3509

http://jsfiddle.net/VixedS/wz95hh3r/1/

$(document).ready(function(){
    $('.original').each(function(){
        $(this).hide().clone().attr('class','new').show().appendTo('body');
    })
});

Upvotes: 1

MurDaD
MurDaD

Reputation: 362

You must use $.each for the element. Starting after you declare $originalEl

$originalEl.each(function(){
    // code here
})

Here is your code updated http://jsfiddle.net/yv1vLhd9/4/

Upvotes: 4

Related Questions