简体   繁体   中英

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.

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>" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM