Reputation: 706
$('button').click(function(){ $(this).prev('label').append('<b>ed</b>').text('Press');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
I want to keep the element <b></b>
or any element exisiting changing the .text()
The steps i'm trying to handle is the following
.append('<b>ed</b>')
at first i appended the new element <b>
;
Driectly after appending the new element i changed the text to Press
.text('Press');
What i'm trying to do is copying the added <b>ed</b>
element before changing the text .text('Press');
then add it again after changing the text()
So it would be like
var element = $(this).prev('label').clone('b');
$(this).prev('label').append('<b>ed</b>').text('Press'+element+'');
The problem i keep getting the element value = [Object object]
Upvotes: 1
Views: 529
Reputation: 28611
In order to access the text part, you need to use .contents()
See this answer and comments for more info.
$("#x").append("<b> pressed</b>")
.contents().filter(function(){return this.nodeType == 3;}).first()
.replaceWith("well done");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='x'>Press</div>
Upvotes: 2
Reputation: 4277
Here is an example using .text() and .append(). Keep in mind that .text()
will replace the element's content in its entirety, so it's important to use .append()
last.
$('button').on('click', function() {
var boldedElem = $(this).prev('label').find('b');
$(this).prev('label').text('Press').append(boldedElem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
Upvotes: 2
Reputation: 4772
Look for all <b>
in this label, take the last one and modify its content using html()
$('button').click(function(){
var label = $(this).prev('label');
label.find('b').last().html('Press');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
Upvotes: 1
Reputation: 48367
Just use .html()
method in order to display the text desired as HTML.
$('button').click(function(){ $(this).prev('label').html('Press<b>ed</b>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
Another solution:
$('button').click(function(){ $(this).prev('label').empty().append('<b>ed</b>').html('Press'+$(this).prev('label').html());
})
Upvotes: 3