Reputation: 31
I am new to jQuery and trying to inject the HTML content of one <div>
into another <div>
.
This is the code I'm using:
<div class="relatedItems"> </div>
<script>
jQuery.noConflict();
jQuery(document).ready(function() {
var related = jQuery("div.itemRelated").html();
jQuery("div.relatedItems").html("<div class='itemRelated'>" + related + "</div>");
});
</script>
The problem is that the injected HTML is not formatted the same way as the original.
I would love to post an image but can't because I'm a new user
Any ideas if I'm missing anything?
Upvotes: 2
Views: 813
Reputation: 237837
This is not the ideal way to copy HTML elements. For the full reason, see my answer to Why should y.innerHTML = x.innerHTML; be avoided?. jQuery can handle this for you in a much more elegant way:
var related = jQuery('div.itemRelated')
.clone(true, true);
jQuery('div.relatedItems').html(related);
This may fix some of your problems, particularly those relating to event handlers. If the styling isn't right, however, you have some specific styling rules that you need to tweak. Use a DOM inspector like the Chrome console or Firebug to examine the relevant elements to see which style are/are not being applied.
Upvotes: 2
Reputation: 18780
You are using the text of an element to attempt to reflect it's current state of appearance, but you are only using the inner element. The most likely causes for the problem you describe are:
To try and solve the first one:
jQuery.noConflict();
jQuery(document).ready(function(){
related = jQuery('div.itemRelated').clone();
jQuery('div.relatedItems').append(related);
});
The second possibility could be discovered by cloning the element into the current elements parent. If the style is correct in the same parent but incorrect in the new parent (relatedItems) then the styles are being supplied by a hierarchical selector and some CSS tweaks will need to be made.
As a general rule you will want to include CSS info when requesting help with a style issue.
Upvotes: 0