124697
124697

Reputation: 21901

How can I apply css to elements created with append()

I am trying to change the text colour of certain options in a but it is not working. none are red

    var style="color:red" 
    $('#newuserSelect')
        .append($('<option>', {
                value: "0",
                title: "hello",
                style: style
            })
            .text("my text"));

http://jsfiddle.net/ZDYEd/ the colour is black when it should be red

Upvotes: 0

Views: 119

Answers (4)

cpreid
cpreid

Reputation: 621

Your JavaScript is fine. You can't color individual options with CSS. This is the output of your original fiddle!

This is your original fiddle

Edited: CSS Text color not taking effect in Chrome 31 for OSX Mavericks enter image description here

enter image description here

Upvotes: -1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Actually, $(xyz).append(abc) will return the object of xyz not abc. And by the way, The proper way to set the css for an element is to use .css() function. Please read here for full reference.

So I would suggest you to use .appendTo in your current context. That will fit your need. Unlike .append(), .appendTo() will return the object of xyz [$(xyz).appendTo(abc)]

Try this,

$('<option>', { value: "0", title: "hello" })
.appendTo('#newuserSelect')
.text('my text')
.css({color:'red'});

DEMO

Upvotes: 2

user1636522
user1636522

Reputation:

Why calling jQuery to create this tiny piece of HTML?

$('#newuserSelect').append(
    '<option value="0" title="hello" style="color:red">my text</option>'
);

Upvotes: 0

Pointy
Pointy

Reputation: 413996

The property name to use is "css", not "style". Also the value should be an object whose properties are the CSS properties to set.

$('#newuserSelect')
    .append($('<option>', {
            value: "0",
            title: "hello",
            css: { color: "red" }
        })
        .text("my text"));

You can, incidentally set the text with that initialization object too:

$('#newuserSelect')
    .append($('<option>', {
            value: "0",
            title: "hello",
            css: { color: "red" },
            text: "my text"
        })
    );

Now, this does work, but it's important to note that when you're looking at the page with the <select> element not "open", you're not looking at the <option> elements. If you want the selected text to be red, then you need to also style the <select> element itself. When there's only one <option>, the <select> cannot be "opened" so you never see the style of the <option>.

I can't recall exactly but it may be the case that IE, or old versions of it anyway, won't pay attention to styles on <option> elements. IE <select> was implemented in a really weird way in old versions.

Upvotes: 3

Related Questions