Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery update html element text without affect the HTML children elements

I have a litle problem and I don't know how to fix it.

I have an HTML hierarchy like the one here

<ul id="mylist">
    <li id="el_01">
        <div class="title">
            Title Goes Here
            <span class="openClose"></span>
        </div>
    </li>
</ul>

What I like to do is to modify the "Title Goes Here".

What I have try is :

$('#el_01 title').text('New Title Goes Here');

But that also remove the :

<span class="openClose"></span>

Is there a way to update only the "Title Goes Here" without affect the span element ?

like image 511
KodeFor.Me Avatar asked Dec 22 '11 15:12

KodeFor.Me


2 Answers

You can edit the text node directly by accessing the DOM element, and getting its firstChild.

$('#el_01 .title')[0].firstChild.data = 'New Title Goes Here';

If there are several .title elements, you can do it in an .each() loop.

$('#el_01 .title').each(function(i,el) {
    el.firstChild.data = 'New Title Goes Here';
});
like image 110
user1106925 Avatar answered Oct 03 '22 08:10

user1106925


Two possible solution:

Either: Wrap the text in a span of its own:

<div class="title">
    <span class="text">Title Goes Here</span>
    <span class="openClose"></span>
</div>

... and update that:

$('#el_01 .text').text('New Title Goes Here');

Or: Keep a copy of the openClose span and re-insert it after updating the text:

var openClose = $('#el_01 .title .openClose');
$('#el_01 .title').text('New Title Goes Here').append(openClose);
like image 25
Peter-Paul van Gemerden Avatar answered Oct 03 '22 06:10

Peter-Paul van Gemerden