0

I'm new to JavaScript. I managed to add dynamic inputs after clicking on a button but I want to know how to apply the CSS to those added inputs, if anyone can give me a simple example i'd be glad! Thank you!

4
  • Like... inline styles? Don't. Add a class and style that. Commented Nov 11, 2014 at 18:03
  • 1
    I agree with @BenPotter, but if you can't change your .css file, you can always use api.jquery.com/css $.css if you have a design library like jQuery Commented Nov 11, 2014 at 18:06
  • I already did that , but the inputs that are added when you click on the add button, have no style ! Commented Nov 11, 2014 at 18:07
  • Please show your code Commented Nov 11, 2014 at 18:08

2 Answers 2

2

Perhaps something like this:

<button onclick="newInput()">Add new input</button>

function newInput() {
    var newElement = document.createElement("input");
    newElement.className = "newClass";
    document.body.appendChild(newElement);
}

And in the style section, or in the .css file, you'll have:

.newClass {
  /*Styles go here*/
    display: block;
}

Fiddle example of the above: http://jsfiddle.net/8zen9wwo/3/

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

Comments

0

Here is a very simple example using jQuery:

http://jsfiddle.net/kmrvpz99/

Html Code

<div class="container"></div>

Javascript Code

$('.container').append('<input type="text" class="yourstyle">');
var manualCss = $('<input type="text">').css('background-color', '#333');
$('.container').append(manualCss);

The css File

.yourstyle {
    background-color: #000;
}

By defining .yourstyle in the css file, all elements on the html site that possess this class, even those dynamically added via javascript, will use this style. You can however manually modify the css by setting the style attribute on the element directly.

Comments

Your Answer

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