RAM RAM - 5 months ago 36
Javascript Question

How to get new jQuery element with new another element inserted after it?

I have this jQuery code:

function test(){
var $h=$('<h2>').text('title')
return $result;

I expect when i show the
in the page, it be:


But it is:


How should i change the code to solve this issue?

I want return this result by calling
function and i wont use any parnet element in the function or as a parameter. Realy i want return this collection of jQuery elements!


This should work

var $h = $('<h2>'),
    $p = $('<p>');

First declare your elements, then set their texts, then append everything in order in the DOM.



If you want to return the newly created objects from the function, you must first create a parent objects for the two <h2> and <p> siblings, and return that object.

function text(){
    var $h = $('<h2>'),
        $p = $('<p>'),
        $container = $('<div>');
    return $container;