jQuery - How can i dynamically add a list item to an unordered list?

13,943

You want to use .appendTo(...) for this style.

$("<li/>").appendTo("#fbsignup .message ul").html("Fields marked with * are required.");​

Try it.

Share:
13,943
RPM1984
Author by

RPM1984

~ Past ~: Mainframes (Model 204, JCL) Java (J2SE, J2EE) Oracle VB.NET ASP.NET Web Forms/MVC ~ Present ~ .NET Core TDD, DDD (all the DDs!) Microservices Containers

Updated on June 04, 2022

Comments

  • RPM1984
    RPM1984 almost 2 years

    Seems like a simple thing to do (although im still learning the ins and outs of jQuery).

    Here's my HTML:

    <div id="fbsignup">
        <div class="message messageerror"> 
           <strong>There were errors with your registration:</strong> 
              <ul></ul> 
        </div> 
    </div>
    

    Here's my (attempted) jQuery:

    // Check Required Fields.
    $('#fbsignup input.required').each(function () {
       if ($(this).val().trim() == '') {
          $(this).next('em').html('*').show();
          $('#fbsignup .message ul').add('li').html('Fields marked with * are required.');
        }
    });
    

    And this is what it is doing to the DOM:

    <div class="message messageerror"> 
       <strong>There were errors with your registration:</strong> 
          <ul>Fields marked with * are required.</ul> 
    </div> 
    

    It's adding the text to the inner html. I want it to add a <li> element with the inner html of what i set - i thought this is how chaining works?

    This is the HTML i want to end up with:

    <div class="message messageerror"> 
       <strong>There were errors with your registration:</strong> 
          <ul>
             <li>Fields marked with * are required.</li> 
          </ul>
    </div>
    

    I also tried this:

    $('#fbsignup .message ul').add('<li>Fields marked with * are required.</li>');
    

    Which does absolutely nothing.

    What am i missing? Is the .add function not the right thing to use here?