If you make the text the value of an input you can bind to it's change
event:
<div id="foo">
<div id="line1">...</div>
<div id="line2"><input type="text" value="foobar" /></div>
</div>
$('#line2').children('input').on('change', function () {
var $this = $(this);
if ($this.val() == '') {
$this.val('new');
}
});
Here is a demo: http://jsfiddle.net/u9Twu/
Note that if you want to programatically change the value of the input you have to manually call .trigger('change')
on the input after you change it's value for the change
event handler to run.
Also note that .on()
is new in jQuery 1.7 and in this case is the same as .bind()
.
UPDATE
var $foo = $('#foo'),
$line2 = $foo.children('#line2');
if ($line2.length == 0) {
//no #line2 element is found
$foo.append('<div id="line2">new</div>');
} else if ($line2.text().length == '') {
//#line2 element is empty
$line2.text('new');
} else if ($line2.text() != 'foobar') {
//#line2 element does not contain only the string: foobar
$line2.text('new');
}
Here is a demo: http://jsfiddle.net/u9Twu/1/