简体   繁体   中英

How do I append any particular tag?

For example I have a list title like this: <li id="example"> title </li> . And here is where I want it to be "appended to" on a click of a button: <ol id="playlist"> </ol>

Here is the button: <span onClick="Button();"><a href="#"> Button </a></span>

Here is the function:

Button=function() {
  $('#playlist').append('#example');
}

I just don't see why it doesn't work I mean when I make the .append('title') - so just plain text - it will add that text to the tag but when I try to append a whole tag through the ID it doesn't? It instead appends "#example" which isn't what I want. I'm sorry I am still trying to grasp this language however, I have honestly searched and scouted the whole internet to try find an anwser to this.

Try this:

$('#playlist').append($('#example'));

Fiddle

Update:

You can use the clone() method, try this:

$('#example').clone().attr('id', 'something').appendTo($('#playlist'))

Fiddle

You need to append the whole li, so your solution would be:

function Button() {
  var $li = '<li id="example"> title </li>';
  $('$playlist').append($li);
}

.append ( content [, content] )

content: DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. ...

jQuery is assuming that you are appending the HTML string #example literally. Use one of the the other two options eg:

$('#playlist').append($('#example')); // append a jQuery object

For the sake of completeness:

$('#playlist').append(document.getElementById('example')); // append a DOM element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM