views:

95

answers:

1

Some elements in my page are rendered through php code. Sometimes, on link clicks that redirect to a page in the same site, I want to insert html elements like div, span etc through javascript in their respective places. My main question is: how do I insert the elements in the appropriate place, and apply the same css styles to them as they would have if they had been inserted through normal flow like php or html code.

For example, suppose I need to insert a div element, which has a span element and an image element inside it, inside a container that has the other elements with the same structure:

<div class="container"><div><span></span><img /></div>...<div><span></span><img /></div> </div>  .

I want to apply same style rules to my inserted elements as there are for other elements. That is, the inserted

<div><span></span><img /></div>

should have the same styles applied as

<style>

.container div {...} .container div span {...} .container div img{...}

But I dont want to manually compute the styles and then add those styles in jquery. How do I do this. The second part of this question is: suppose there are conditional styles applied depending on the browser. Now, how do I apply the conditional styles depending on the browser, without trying to do it manually?

+1  A: 

If you create your element using jQuery, simply use addClass() to add the container class to the parent <div> as such:

var new_div = $('<div/>').addClass('container');
// or (whatever floats your boat)
var new_div = $(document.createElement('div')).addClass('container');

It will then be styled as any other div.container on your page.

If you are getting your elements via AJAX, make sure that the HTML you are sending already have the class applied.

If you are simply adding elements inside your <div class="container"> via jQuery, they automatically follow the same style as the rest of the elements based on the markup you posted without any added code.

// The inserted elements automatically follows the rules
// in the internal and external stylesheet.
var container = $('div.container:first').append('<div><span></span><img /></div>');

It does not however automatically copy inline styles. Those should be moved to either an internal or external style-sheet.

Personally, I find that inline styles are usually code-smells unless used for last-minute width and height purposes in variable-size boxes situations.

Andrew Moore
Andy, why not $('<div />').addClass....
redsquare
No idea why I went for document.createElement...
Andrew Moore
`$(document.createElement('div'))` is a little bit faster because jQuery doesn't have do any parsing.
Sidnicious