andy4thehuynh
andy4thehuynh

Reputation: 2172

Would appending to a non existing element create a new instance of that element in JQuery?

In my browser, I have a textbox and a submit button. Using the text from the textbox, I want to add that text as a list item at the end of an unordered list. The unordered list does not exist yet but I want the text to appear under the textbox and submit button. I made this function:

Code:

 function display(text) {                       // 'text' from the textbox
      $('ul').append('<li>' + text + '</li>');
 }

When I use .display(), I want to be able to display the text in the parameter as a new list item in an unordered list.

Question: Does JQuery create a new 'ul' if one doesn't exist yet or should I create one first? If so, am I using JQuery correctly to add a list item to the unordered list?

Any advice helps! Thanks!

Upvotes: 1

Views: 361

Answers (2)

Michael Geary
Michael Geary

Reputation: 28870

Your $('ul') selector creates a jQuery array containing every <ul> element on your page. If there are no <ul> elements, the array is empty. If you want a <ul> element and there isn't one, you need to create it yourself, which of course you can easily do with jQuery.

The way you're appending the <li> element is fine, but it won't do anything if there is not a <ul> on the page.

Also you really shouldn't be selecting by tagname like this. What if there is more than one <ul> on the page? You should select it by id or class.

Upvotes: 1

pktangyue
pktangyue

Reputation: 8534

First you must use $('<ul>') to create a new <ul>, while $('ul') select the already existed element.

For more information, see jQuery( html [, ownerDocument ] )

Then you can rewrite you code like this:

var ul = $('<ul>');  // save the new created element.
ul.appendTo('body')  // add it into <body> or other place you want to insert
function display(text) {                       // 'text' from the textbox
      ul.append('<li>' + text + '</li>');
 }

Upvotes: 2

Related Questions