Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to jQuery selector for content just added via manipulation method?

Tags:

jquery

If content is added to the DOM using, e.g.,

$("ul").append("<li>test</li>");

how does one get a reference the content just added w/o having to select the newly added content?

Assigning the return value from the append() method is the jQuery object.

var newContent=$("ul").append("<li>test</li>");

One could do

var newContent=$("ul li:last");

but is there a way to get it more directly?

Thanks

like image 652
ChrisP Avatar asked Feb 01 '10 19:02

ChrisP


People also ask

What is the correct way of selecting the current element with jQuery selectors?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Can you can use CSS3 selectors to select or find elements using jQuery?

In fact, you can use any CSS selector (even CSS3 selectors) in jQuery.

Which of the following jQuery methods get the input value of an element?

The val( ) method gets the input value of the first matched element. Q 18 - Which of the following jQuery method set the value of an element?

How do you select the first element with the selector statement?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).


2 Answers

Use .appendTo():

Insert every element in the set of matched elements to the end of the target...

The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container...

like image 140
micahwittman Avatar answered Oct 21 '22 06:10

micahwittman


You can create it in its own line ala:

var newLi = $('<li>test</li>');
$('ul').append(newLi);

//Continue using newLi and it will affect the appended element
like image 24
Michael La Voie Avatar answered Oct 21 '22 04:10

Michael La Voie