-2

With this code I create a <select> element:

$('ul.category-list').each(function () {
    var list = $(this),
        select = $(document.createElement('select')).insertBefore($(this).hide()).change(function () {
            window.location.href = $(this).val();
        });
    $('>li a', this).each(function () {
        var option = $(document.createElement('option'))
            .appendTo(select)
            .val(this.href)
            .html($(this).html());
        if ($(this).attr('class') === 'selected') {
            option.attr('selected', 'selected');
        }
    });
    list.remove();
});

How do I give the <select> element an id or class so I can control it with CSS?

JJJ
  • 32,902
  • 20
  • 89
  • 102
  • Use jQuerys addClass method , given that you seem to be using it, just call it on the element you want with the wanted class as a string parameter. – martin.code Jun 08 '14 at 21:02
  • http://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element – David Corbin Jun 08 '14 at 21:03
  • 6
    btw instead of mixing jQuery and plain javascript I'd suggest you pick one and stick to it. That'd be much less of a mess. – source.rar Jun 08 '14 at 21:04
  • Just as you reference some things with variables, try referencing other things with variables. In this case: `var newSelect = document.createElement('select'); newSelect.className = "abc123class";` – Niet the Dark Absol Jun 08 '14 at 21:10
  • 1
    @source.rar: Using jQuery **is** using "plain JavaScript." jQuery is just a library. If you mean the DOM, say the DOM. The JavaScript is just as plain either way. – T.J. Crowder Jun 08 '14 at 21:11
  • Valid point, but I'm sure they meant "syntax" wise. Mixing the 2 shows that there is probably a lot of copy and pasting - and not a ton of understanding. – sheriffderek Jun 08 '14 at 22:15

1 Answers1

0

HTML

<div class="an-element"></div>


CSS

.your-class {
    color: orange;
}


javascript, (using the jQuery library's write-less do-more methods and syntax)

$(".an-element").append("<div class='your-class'>Test</div>");


a jsFiddle

sheriffderek
  • 8,848
  • 6
  • 43
  • 70