How to dynamically create / add list items (ul, ol, li) using jQuery DOM manipulations?

I am programming an AJAX webpage (using IE 8) and I need to dynamically create a list in jQuery based on the returned data. Later I will convert the list to jQuery accordian.

I am also trying to learn how to properly use these jQuery functions and chains. I'm just jQuery NOOB, but I understand JavaScript. I found a good article about jQuery dom functions: http://www.packtpub.com/article/jquery-1.4-dom-insertion-methods

I want to add as much as possible using the jQuery dom functions and jQuery chains without resorting to the HTML source code using text. I want to basically use the .wrap(), .appendto(), .attr(), .text()and .parent().

I don’t think that “ .attr("class", "CC_CLASS").This is the best way to add a class.

Given the HTML code:

<div id="outputdiv"></div>

Use jQuery dom functions to change it like this:

<div id="outputdiv"> 
 <ul id="JJ_ID"> 
  <li> AAA_text </li> 
  <li id="BB_ID"> BBB_text </li> 
  <li class="CC_CLASS"> CCC_text </li> 
  <li id="DD_ID">DDD_text<br/> 

    <ol id="EE_ID"> 
      <li> FFF_text </li> 
      <li id="GG_ID"> GGG_text </li> 
      <li class="HH_CLASS"> HHH_text </li> 
    </ol> 

  </li> 
 </ul> 
</div>

I understood some code (ignoring spaces in the text).

var aObj = $('<li></li>').text("AAA_text")
var bObj = $('<li></li>').attr("id", "BB_ID").text("BBB_text"); 
var cObj = $('<li></li>').attr("class", "CC_CLASS").text("CCC_text");
var dObj = $('<li></li>').attr("id", "DD_ID").text("DDD_text");
var fObj = $('<li></li>').text("FFF_text");
var gObj = $('<li></li>').attr("id", "GG_ID").text("GGG_text"); 
var hObj = $('<li></li>').attr("class", "HH_CLASS").text("HHH_text"); 

How do I add (fObj + gObj + hObj) to eObj?

var eObj = '*something*'.attr("id", "EE_ID").wrap('*something*');

Somehow add (aObj + bObj + cObj + dObj + eObj) to jObj?

var jObj = '*something*'.attr("id", "JJ_ID").wrap('*something*');  
jObj.appendTo("#xmlOutputId")
+3
source share
2 answers

The method .appendreturns the same container object that you called it on - use this to hook methods nicely:

var inner_list = $('<ol/>', {id: "EE_ID" })
    .append( $('<li/>', {text: "FFF_text" })
    .append( $('<li/>', {id: "GG_ID", text: "GGG_text" })
    .append( $('<li/>', {"class": "HH_CLASS", text: "HHH_text" });

var outer_list = $('<ul/>', {id: "JJ_ID" })
    .append( $('<li/>', {text: "AAA_text" })
    .append( $('<li/>', {id: "BB_ID", text: "BBB_text" })
    .append( $('<li/>', {"class": "CC_CLASS", text: "CCC_text" })
    .append( 
        $('<li/>', {id: "DD_ID", text: "DDD_text"})
        .append(inner_list)
    );

outer_list.appendTo('#xmlOutputId');

In fact, you can do everything in one statement without vars, but in my opinion it will be too ugly.

+7
source
0

Source: https://habr.com/ru/post/1786052/


All Articles