简体   繁体   中英

change text of an element without changing child elements

 $('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]

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());
})

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> 

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM