Reputation: 353
In my application I am applying some CSS onload and then appending some html using Jquery! My problem is that CSS is not being applied to the newly added element. How can i make sure that the CSS is applied to newly appended html?
Please have a look at jsfiddle
HTML:
<body onload="loaded()">
<div id="a">
<div class="main">a</div>
<div class="main">b</div>
<div class="main">c</div>
<div class="main">d</div>
</div>
<input type="button" value="click Me" onclick="clickMe()" />
</body>
JAVASCRIPT:
function loaded() {
var posts = $('.main'),
postCount = posts.length,
postHalf = Math.round(postCount / 2),
wrapHTML = '<div class="tab"></div>';
posts.slice(0, postHalf).wrapAll(wrapHTML);
posts.slice(postHalf, postCount).wrapAll(wrapHTML);
}
function clickMe() {
$("#a").append("<div class='main'>e</div>");
}
CSS:
.tab {
width: 10%;
border: 1px solid black;
float: left;
}
Upvotes: 1
Views: 2398
Reputation:
Your newly added element has class .main
, and in css you have .tab
, so no css will be applied to your new element obviously.
IF I understand correctly what you want to achieve, I'd say you need to re-run loaded() function once new element is added. So new div is wrapped in .tab
div, just like it happens onload for existing elements.
But you will need to unwrap elements before you call loaded() function, otherwise some weird things will happen. Like so:
function loaded() {
var posts = $('.main'),
postCount = posts.length,
postHalf = Math.round(postCount / 2),
wrapHTML = '<div class="tab"></div>';
posts.slice(0, postHalf).wrapAll(wrapHTML);
posts.slice(postHalf, postCount).wrapAll(wrapHTML);
}
function clickMe() {
$('.main').unwrap();
$("#a").append("<div class='main'>e</div>");
loaded();
}
THIS should work fine: http://jsfiddle.net/MfSga/6/
Besides, don't use onload onclick inside html. Do it in js file.
Upvotes: 1