0

Hi I am trying to create programmatically the following HTML section in a specific div, by inserting the Dropdown name and Drop Item. Thank you for any help.

<ul class="nav">
        <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle">Dropdown 1</a>
            <ul class="dropdown-menu">
                <li>
                    <a href="#">Drop Item 1</a>
            </li>
        </ul>
    </li>
</ul>

In simple, I would like to create 1 or 2 methods which accepts 2 strings, 1 for the Dropdown and the other for the Drop Item

1
  • $('yourHtmlStringHere').appendTo('#targetElement') Commented Aug 16, 2016 at 10:50

2 Answers 2

1

try this:

var str='<ul class="nav"><li class="button-dropdown">';
          str+=  '<a href="javascript:void(0)" class="dropdown-toggle">Dropdown 1</a>';
             str+= '<ul class="dropdown-menu"><li><a href="#">Drop Item 1</a></li></ul></li></ul>';

$('#div-id').html(str);

div-id is your specific div ID .

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

Comments

1

as @Nihar Sarkar pointed but with the function with the two strings

function updateList(Dropdown1,DropItem1List){

    var ListOfItems = '';

    for(var i=0; i<DropItem1List.length;i++){
        ListOfItems +=  '<li><a href="#">'+DropItem1List[i]+'</a></li>';
    }

    var htmlCode = '<ul class="nav">'
            +'<li class="button-dropdown">'
                +'<a href="javascript:void(0)" class="dropdown-toggle">'+Dropdown1+'</a>'
                +'<ul class="dropdown-menu">'
                    +ListOfItems
            +'</ul>'
        +'</li>'
    +'</ul>';

    $('#yourDivId').html(htmlCode);

}

or if the html already exists in your page

$('#yourDivId .nav .button-dropdown a.dropdown-toggle').text(Dropdown1);
$('#yourDivId .nav .button-dropdown ul.dropdown-menu').text(DropItem1);

7 Comments

Thank you for the reply. What if I would like to append, for example if I keep press the new will be added? Also, there is a way to add multiple DropItem, fr example in a loop?
try the new version of code to add multiple DropItem haven't tested but it should work
$('#yourDivId .nav .button-dropdown ul.dropdown-menu').append('<li><a href="#">'+Item+'</a></li>'); to add one single item to the list
It works but I can only see only the Dropdown1, DropItem1List is not visible.
DropItem1List will be a array of strings you want as options of the list for example var DropItem1List =['option1','option2','option3'];
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.