Yash Yash - 2 months ago 7
CSS Question

How to append a span tag inside another span tag in jquery?

I have the following code in jquery in which I am trying to add a child under a parent span tag:


var branchName = $(this).closest('tr').find('#adjNcmcompanyNameId').text();
var branchId = $(this).closest('tr').find('#adjNCMBranchIdForSearch').text();
var branchRecord = $(this).parents().find('#resultsection');
branchRecordSpan = ("<span class='multiselectContainer'></span>");
branchRecordSpan.append("<span class='indivSelectedText'>" + branchName + "</span>");
branchRecordSpan.append("<input class='indivSelectedValue' type='hidden' value=" + branchId + ">");
branchRecordSpan.append("<strong class='alert-pink'><i class='fa fa-chevron-left fa-lg'></i></strong>");

html that I am trying to get

<div id="resultsection">
<span class="multiselectContainer" id=
"c85a47e3-40c0-48e1-95f0-89dd761dbb56"><span class=
"indivSelectedText">MY BRANCH</span> <input class="indivSelectedValue"
type="hidden" value="183424"> <strong class="alert-warning"><i class=
"fa fa-chevron-left fa-lg"></i> <i class="fa fa-database"></i>
,DATAHUB/ 8683403</strong> <a class="fa fa-times-circle labelclose"

Since all the content are under the multiselectContainer span class, I am trying to generate html dynamically using append and I am failing.
When I try to append under branchRecordSpan, it is throwing an error as it is not a function. I am not able to create child for the "multiseleccontainer" span class.

How can I create a span tag dynamically under another span tag? Please help.


Do it in stages.

x = $('<span>parent span</span>');
x.append('<span>new child span</span>');


Or just do it directly:

x = $('<span>parent<span>child</span></span>');

The second option is generally more efficient. Every time you .append() something to the DOM, there's fair amount of background work to parse/modify/re-render/etc... It's generally best to build html as a string, then insert it into the DOM in one big chunk, rather than a series of smaller chunks.