jquery - How to Apply CSS to element added by Javascript -


in application applying css onload , appending html using jquery! problem css not being applied newly added element. how can make sure css applied newly appended html?

please have @ 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; } 

your newly added element has class .main, , in css have .tab, no css applied new element obviously.

if understand correctly want achieve, i'd need re-run loaded() function once new element added. new div wrapped in .tab div, happens onload existing elements.

but need unwrap elements before call loaded() function, otherwise weird things happen. 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. in js file.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -