Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

javascript - jQuery - setting an element's text only without removing other element (anchor)

I have an element like this:

<td>
  <a>anchor</a>
  [ some text ]
</td>

And i need to set it's text in jQuery, without removing the anchor.

The element's contents could vary in order (text before or after), and the actual text is unknown.

Thanks

New Update

This is what i came up using, assumes only a single text node:

    function setTextContents($elem, text) {
        $elem.contents().filter(function() {
            if (this.nodeType == Node.TEXT_NODE) {
                this.nodeValue = text;
            }
        });
    }

    setTextContents( $('td'), "new text");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Neal's answer is my suggestion. jQuery doesn't have a way to select text nodes How do I select text nodes with jQuery?.

Changing your HTML structure will make for the simplest code. If you can't do it, you can just use the childNodes property looking for nodes of type 3 (TEXT_NODE)

Here's some sample code that assumes the last node is the node you want to edit. This is a better approach than replacing the entire contents of the td because you could lose event handlers when you recreate the HTML

$('a').click(() => console.log('<a> was clicked'))

$('#btn').click(() =>
  $('.someClass').get(0).lastChild.nodeValue = " New Value");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='someClass'>
  <a href="javascript:void(0)">anchor</a> [ some text ]
</div>

<button id='btn'> Change text without losing a tag's handler</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...