pcoving
pcoving

Reputation: 2788

Styling of dynamically added jQuery elements

Here's the demo:

http://jsfiddle.net/JH7SU/1/

I'm confused as to why identical markup would appear different, depending on whether it is delivered statically or on load. I'm guessing it's related to how the DOM is parsed and the style is somehow not properly inherited from the parent element?

The context is that I'm designing an interactive form whose logic is too complex to just hide/show elements. Hence I'd like to create/destroy new elements on the fly (but with proper CSS).

Thanks for your help!

Upvotes: 1

Views: 164

Answers (4)

Alfred
Alfred

Reputation: 21396

It is because, in your static html, select and input are in two lines, means there is some space in between them. If you want to get this in dynamic, you have to add a space there too.

Here is a working fiddle.

But I strongly recommend you to avoid this kind of positioning and use Strict CSS styling for margin and padding. Here is the corrected fiddle using CSS.

Upvotes: 2

TWickz
TWickz

Reputation: 632

It's just the way that the html gets appended in your code. It's different from how you type it for real. Funnily enough this will work for you.

dynamicControls.append(dynamicSelect);
dynamicControls.append('\r\n');
dynamicControls.append(dynamicInput);

Upvotes: 0

Barmar
Barmar

Reputation: 780994

It's the usual problem: whitespace. Your static form has a newline between </select> and <input>, which gets turned into a blank in the form. But when you append the elements dynamically there's nothing between them.

Change it to:

dynamicControls.append(dynamicSelect, ' ', dynamicInput);

and they both look the same.

Or if you prefer the look of the dynamic element, get rid of the whitespace in the static version.

Upvotes: 0

Jeff Camera
Jeff Camera

Reputation: 5544

The select and input elements are styled as inline-block so they are treated as inline elements with space between them if space exists in the markup.

Either insert a space or line break before appending the dynamic element or remove the line break in your static element.

Example with no space: http://jsfiddle.net/bhJg8/ Example with space: http://jsfiddle.net/fr5W7/

Upvotes: 0

Related Questions