RAM RAM - 1 month ago 4
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')
$p=$('<p>').text('sample'),
$result=$h.after($p);
return $result;
}


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

<h2>title</h2><p>sample</p>


But it is:

<h2>title</h2>


How should i change the code to solve this issue?




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

Answer

This should work

var $h = $('<h2>'),
    $p = $('<p>');
$h.text('title');
$p.text('sample');
$('body').append($h);
$h.after($p);

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

https://jsfiddle.net/jhjoorbc/

Edit

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>');
    $h.text('title');
    $p.text('sample');
    $container.append($h).append($p);
    return $container;
}
Comments