<div data-component-id="nwv4kv9j5ct9" class="component-inner-container status-red " data-component-status="major_outage" data-js-hook="" id="nwv4kv9j5ct9">
<span class="name table-item-name">JHP</span>
<span class="service-tier table-item-tier"><a href="" target="_blank"
onclick="event.stopPropagation()">Tier 2</a></span>
<span class="tooltip-base tool tooltipstered" style="display: none;">?</span>
<span class="component-status table-item-status-childs" title=""><span class="app-status bg-
inactive">failing</span></span>
<span class="tool icon-indicator fa fa-times tooltipstered"></span>
</div>
<div data-component-id="rtv4kv9j5cyu" class="component-inner-container status-red " data-component-status="major_outage" data-js-hook="" id="nwv4kv9j5ct9">
<span class="name table-item-name">PHS</span>
<span class="service-tier table-item-tier"><a href="" target="_blank"
onclick="event.stopPropagation()">Tier 2</a></span>
<span class="tooltip-base tool tooltipstered" style="display: none;">?</span>
<span class="component-status table-item-status-childs" title=""><span class="app-status bg-inactive">degrading</span></span>
<span class="tool icon-indicator fa fa-times tooltipstered"></span>
</div>
......
......
I need to create and append a span tag <span class="type table-item-type">Type</span>
inside each div with class name component-inner-container
. It should be after
$('.component-inner-container').each(function () {
var span = $('<span />').attr('className', 'type')
span.appendTo(".component-inner-container");
});
I’m stuck here and couldn’t able to find right approach
Edit : added span should be after for example <span class="name table-item-name">PHS</span>
3
Answers
You can try do it this way:
I’ve changed your
span.appendTo(".component-inner-container");
tospan.appendTo(this)
, since I think you only want one span in each container.Demo
The issue is because in your loop you append to every
.component-inner-container
. Therefore you end up with N copies in each parent, where N is the length of your loop.To fix the problem, just call
append()
directly on the jQuery object holding all.component-inner-container
elements.Also note that you should use
prop()
when setting theclassName
property, and also that it’s better to useaddClass()
in either case.It will append the span to all elements with class "component-inner-container".