Kostar
Kostar

Reputation: 47

jQuery how to replace all contents of an element into another?

Say I have 3 elements like below with different html contents:

<div id='result1'> <p>One</p> </div>
<div id='result2'> <p>Two</p> </div>
<div id='result3'> <p>Three</p> </div>

How can I copy just contents within the div element to the next one so that the final result looks like this?

<div id='result1'> <p>New content</p> </div>
<div id='result2'> <p>One</p> </div>
<div id='result3'> <p>Two</p> </div>

There will be new content for replacement and the last content can be discarded. To clarify, I'll have something like:

<div id='new'> <p>New content</p> </div>

where I want to grab '<p>New content</p>' as new content to use.

What do you think?

Upvotes: 0

Views: 108

Answers (3)

Anil
Anil

Reputation: 3752

try JS fiddle

I am suggesting to add a Parent Grid and use jquery first() and last(), These controls will function like a queue.

$('#Pdiv').children().last().remove();
$('#Pdiv').first().prepend("<div id='new'> <p>I am New One</p></div>");

alert($('#Pdiv').children().first().html());

Upvotes: 0

Adil
Adil

Reputation: 148110

You can use .html() on the element you want to change the content. For accessing particular element you can use ID Selector (“#id”) with Child Selector (“parent > child”).

Live Demo

$('#result1 > p').html('New content');

Edit to move contents to next elements you can iterate through all elements and start assigning the context of second last to last, third last to second last and so on

Live Demo

elements = $('[id^=result] > p');
len = elements.length;
elements.each(function(idx, el){
   if(idx == elements.length-1) return; 
   $('#result'+ (len-idx) + ' p').html($('#result' + (len-idx-1) + ' p').html());   
});

$('#result1 > p').html('New content');

Upvotes: 1

adeneo
adeneo

Reputation: 318182

To push the content down, reverse the collection and set the HTML to the HTML of the previous one.

var elems = $($('[id^=result]').get().reverse());

elems.html(function(i) {
    return elems.eq(i+1).html();
}).last().html('New Content');

FIDDLE

Upvotes: 2

Related Questions