0

I'm using jQuery to add elements dynamically to a dropdown but I think I'm mixing syntaxes and would like to go pure jQuery. Currently I'm doing this:

$("#data-source-menu").addClass("menu-container") .html($("<ul class=\"popup-menu\" id=\"dataset-menu\"><\/ul>"));

Then later

$("#dataset-menu").append($("<div>" + dataset.label + "<\/div>").addClass("menu-item").attr(dataset));

It's that inner building of the html I don't like. Is there a more abstract way to approach this that doesn't involve writing html? Something like JavaScript's document.createTextNode("Hello")?

1 Answer 1

3

That should be better:

$('#data-source-menu').addClass('menu-container').html(
    $('<ul/>').addClass('popup-menu').attr('id', 'dataset-menu').append(
        $('<div/>').text(dataset.label).addClass('menu-item')
    )
);

and here's the live demo.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, This should be classified the "proper" way, as it's compartmentalizing functionality and avoiding any kind of intervening (albeit script variables, cookie values, etc.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.