cgrclk
cgrclk

Reputation: 3

How to create a new html element in javascript?

I am working on a menu. This script create select menu. I want to add <label> tag.

Output;

<select name="select_box" id="select_box">
</select>

What I want;

<label>
<select name="select_box" id="select_box">
</select>
</label>

Script;

$(function() {

var select = $('<select name="select_box" id="select_box">').appendTo('#nav');
    $('#nav li').each(function() {
        var li = $(this),
            a = li.find('> a'),
            p = li.parents('li'),
            prefix = new Array (p.length + 1).join('-');
        var option = $('<option>')
            .text(prefix + ' ' + a.text())
            .val(a.attr('href'))
            .appendTo(select);
    });
});
$(function() {
    $("<option>", {
        "selected": "selected",
        "value": "",
        "text": "Menü Seçiniz..."
    }).prependTo("#nav select");
});
$(function() {
    $('#nav select').on('change', function() {
        var url = $(this).val();
        if (url) {
            window.location = url;
        }
        return false;
    });
});

Maybe this is very simple question but i don't have any idea how to do that. Sory my bad language. I'm waiting for your help.

Upvotes: 0

Views: 62

Answers (1)

cardeol
cardeol

Reputation: 2238

To add a new element:

var $newlabel = $("<label />").html($("#select_box"));

Or edit your line to

var select = $('<label><select name="select_box" id="select_box"></label>').find("select");

Or wrap your element with the select element

var select = $('<select name="select_box" id="select_box" />');
select.wrap( "<label></label>" );

Upvotes: 1

Related Questions