Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text in div without affecting child elements

I need to modify the following HTML using Javascript,

<div id="1">
   some text
   <div id="2"></div>
</div>

I have tried using $('#1').text('new text'); However, this unintentionally removes <div id="2">

How should I change some text, without changing the surrounding elements?

like image 687
Constantine Gladky Avatar asked Jun 30 '14 15:06

Constantine Gladky


1 Answers

This will change the value of the first node (which is a text node in your example):

$('#1').contents()[0].nodeValue = 'new text';

JSFiddle

like image 71
Tony Dinh Avatar answered Sep 29 '22 20:09

Tony Dinh