I'm playing around with dynamically loaded HTML content on a webpage I am building. What I want is to have a list of HTML files with snippets that will be dynamically imported into my webpage using javascript/jquery and an ajax request. This would allow me to e.g. store several blog posts as separate files and dynamically build a page with multiple posts on it.
Below is an example snippet with just a title and a small table:
CSS :
#swimTimes2{
background-color: #eee;
}
HTML SOURCE :
<div id="itemContainer">
<div id='swimTimes2' class='item'>
<h1> Swim Times </h1>
<table>
<tr class="tableHead">
<td>Weekdays</td><td>Weekends</td><td>Holidays</td></tr>
<tr>
<td>7:00am-9:00am</td><td>10:30am-8:00pm</td><td>11:00am-4:00pm</td></tr>
<tr>
<td>11:00am-2:00pm</td></tr>
<tr>
<td>4:00pm-10:30pm</td></tr>
</table>
</div>
</div>
I figured out that by using $.get() I can load the contents of my snippet file above and then use jquery to search through it for the html snippet I want, in this case the contents of #itemContainer.
JAVASCRIPT
$(document).ready( function(){
loadContent('content/content_1.html');
});
function loadContent(fileName){
$.get(fileName, function(data){
var htmlContents = $(data).find("#itemContainer").children('.item').html();
var id = $(data).find("#itemContainer").children('.item').attr('id');
$('#content').append($('<div class="item" />').attr('id', id).html(htmlContents));
var styleEl = $(data).find("style");
$('head').append(styleEl);
});
}
So the first 3 lines of my $.get() handler function work - I am able to import the snippet and put it up on my html page. Now I want to import also the css styles from the snippet into my main page - in this example I gave my item a grey background, a property that it wouldn't get from my main html page.
The issue I have is that although I know the style element from my snippet is being imported into my main page, the css rules it contains are not applied to the imported html. What am I missing?
ifram? Otherwise, you might have issues having two<html>,<head>and<body>tags.#itemContaineras a string and interpreting it as a jquery element, then appending it to a div on my main page.<style>item in the head