1

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;
}
2
  • 1
    Check markup in developer tools you'll see what's going on. Commented Oct 6, 2013 at 23:55
  • 1
    what css rule are u talking abt? Commented Oct 6, 2013 at 23:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Sandro-Dzneladze It worked! I am not aware of unwrap()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.