Organizational Research By

Surprising Reserch Topic

how can i change an elements text without changing its child elements


how can i change an elements text without changing its child elements  using -''

I'd like to update element's text dynamically:

<div>
   **text to change**
   <someChild>
       text that should not change
   </someChild>
   <someChild>
       text that should not change
   </someChild>
</div>


I'm new to jQuery, so this task seems to be quite challenging for me.
Could someone point me to a right function/selector to use?

If it is possible, I'd like to do it without adding a new container for the text I need to change.

Thanks in advance.
    
asked Sep 14, 2015 by Bea81N
0 votes
10 views



Related Hot Questions



Government Jobs Opening

" rel="nofollow" target="_blank">https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
Some text
Child1
Child2
Child3
Child4
answered Sep 14, 2015 by MalChristie
0 votes

For the specific case you mentioned:

**text to change** text that should not change text that should not change

... this is very easy:

var div = document.getElementById("foo");
div.firstChild.data = "New text";

You don't state how you want to generalize this. If, say, you want to change the text of the first text node within the

, you could do something like this:

var child = div.firstChild;
while (child) {
    if (child.nodeType == 3) {
        child.data = "New text";
        break;
    }
    child = child.nextSibling;
}
answered Sep 14, 2015 by JenniferKeye
0 votes

Just wrap the text you want to change in a span with a class to select.

Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple


Voilà!

$('#header .mytext').text('New text here')
answered Sep 14, 2015 by AnkRowland
0 votes

Here is yet another method : http://jsfiddle.net/qYUBp/7/

HTML


JQUERY

var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);
answered Sep 14, 2015 by GinZgu
0 votes

Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:

$.fn.textnodes = function () {
    return this.contents().filter(function (i,n) {
        return n.nodeType == 3 && n.textContent.trim() !== "";
    });
};

$("div").textnodes()[0] = "changed text";
answered Sep 14, 2015 by BillKissner
0 votes

I think you're looking for .prependTo().

http://api.jquery.com/prependTo/

We can also select an element on the page and insert it into another:

$('h2').prependTo($('.container'));

If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

Greetings

Hello
Goodbye

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

answered Sep 14, 2015 by GenKoertig

...