user3822284
user3822284

Reputation:

Adding CSS to and added input elements using Javascript

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!

Upvotes: 0

Views: 69

Answers (2)

Xenyal
Xenyal

Reputation: 2223

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/

Upvotes: 2

peacer212
peacer212

Reputation: 955

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.

Upvotes: 0

Related Questions