How to create dynamic HTML tags

How to create HTML tags dynamically?

In some cases, there might be a requirement to create HTML tags dynamically.
For eg, I will create below HTML structure with C# code.
<ul id=”pagelist” runat=”server” class=”pages”>
<li class=”active” rel=”page1″>My Page Title1</li>
<li rel=”page2″>My Page Title2</li>
</ul>
<div class=”container” id=”container” runat=”server”>
<h3 rel=”page1″></h3>
<div id=”page1″>    </div>
<h3 rel=”page2″></h3>
<div id=”page2″>    </div>
</div>
First create <ul> and <li> structure:
    private void CreateLists(int liCount)
    {
        for (int i = 1; i <= liCount; i++)
        {
            HtmlGenericControl liCtrl = new HtmlGenericControl(“li”);
            if (i == 1)
            {
                liCtrl.Attributes.Add(“class”, “active”);
            }
            liCtrl.Attributes.Add(“rel”, “page” + i);
            liCtrl.InnerHtml = “Test Content”;
            tabsList.Controls.Add(liCtrl);
        }
    }

Now create <div> and <h3> structure


private void CreateContentArea(int Count)
    {
        for (int i = 1; i <= Count; i++)
        {
            HtmlGenericControl h3Tag = new HtmlGenericControl(“h3”);
            h3Tag.Attributes.Add(“rel”, “page” + i);
            h3Tag.InnerHtml = “Dummy content”;
            tabsContainer.Controls.Add(h3Tag);
            HtmlGenericControl div = new HtmlGenericControl(“div”);
            div.Attributes.Add(“id”, “page” + i);
            div.InnerHtml = “Another Dummy content”;
            tabsContainer.Controls.Add(div);
        }
    }
Please follow and like us:

Leave a Comment