最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery update html element text without affect the HTML children elements - Stack Overflow

programmeradmin0浏览0评论

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 ?

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 ?

Share Improve this question asked Dec 22, 2011 at 15:25 KodeFor.MeKodeFor.Me 13.5k28 gold badges102 silver badges172 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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

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);
发布评论

评论列表(0)

  1. 暂无评论