John
John

Reputation: 1751

jQuery append to existing element  

I have the following html code:

<a class="dropdown-toggle" id="ddaccount" aria-expanded="false">
    <i class="fa fa-lock"></i>&nbsp;
    <span class="hidden-sm hidden-md hidden-lg">User Account</span>
    <span class="caret"></span>
</a>

I need to replace &nbsp; with &nbsp; USER

I try usint this jQuery code but it insert at then end of a tag not repalce existing &nbsp;:

$('a#ddaccount').append('USER');

So i need to get this:

<a class="dropdown-toggle" id="ddaccount" aria-expanded="false">
    <i class="fa fa-lock"></i>&nbsp;USER
    <span class="hidden-sm hidden-md hidden-lg">User Account</span>
    <span class="caret"></span>
</a>

And i get this:

<a class="dropdown-toggle" id="ddaccount" aria-expanded="false">
    <i class="fa fa-lock"></i>&nbsp;
    <span class="hidden-sm hidden-md hidden-lg">User Account</span>
    <span class="caret"></span>
    &nbsp;USER
</a>

I try using first() after() i element but none works?

Upvotes: 0

Views: 110

Answers (2)

SilverSurfer
SilverSurfer

Reputation: 4365

Use replace():

$('a#ddaccount').html($('a#ddaccount').html().replace(/&nbsp;/g, '&nbsp;USER'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a class="dropdown-toggle" id="ddaccount" aria-expanded="false">
    <i class="fa fa-lock"></i>&nbsp;
    <span class="hidden-sm hidden-md hidden-lg">User Account</span>
    <span class="caret"></span>
</a>

Upvotes: 1

Kiran Dash
Kiran Dash

Reputation: 4956

What you are doing is append() which simply adds the content to the end of the html content.

What you should be doing is get the entire html content and then in it replace &nbsp; with &nbsp;USER and then assign it back to the html.

DEMO

$('a#ddaccount').html($('a#ddaccount').html().replace(/&nbsp;/g, '&nbsp;USER'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="dropdown-toggle" id="ddaccount" aria-expanded="false">
    <i class="fa fa-lock"></i>&nbsp;
    <span class="hidden-sm hidden-md hidden-lg">User Account</span>
    <span class="caret"></span>
</a>

Upvotes: 1

Related Questions