Mo.
Mo.

Reputation: 27465

How to change text except its span

How can we change the text data from except span text?

<h2 id="nameUser" >Muhammed <span> mobile :989 531 9991</span></h2>

Is there any solution to change h2 except span?

Upvotes: 0

Views: 142

Answers (7)

Dario
Dario

Reputation: 437

try this ...

<h2 id="nameUser" >Muhammed <span id="nameUserSpan"> mobile :989 531 9991</span></h2>

<script>
$(document).ready(function() {
    var inspan= $("#nameUserSpan").html();
    var newuser='New User';
    $("#nameUser").html('');
    $("#nameUser").html(newuser + '<span id="nameUserSpan">' + inspan + '</span>');
});
</script>

Upvotes: 0

Bruno Vieira
Bruno Vieira

Reputation: 3904

This will work not only for span but also for any other element which you want the text without the text of it's children.

$("#nameUser")
    .clone()   
    .children()
    .remove()  
    .end()  
    .text();

For change the text I've create a simple jQuery function:

replaceTextWith = function($element, $replacement){
    $oldText = $element.clone().children().remove().end().text();
    $element.text($element.text().replace($oldText, $replacement));
}

replaceTextWith($("#nameUser"), "Bruno"); //usage

Here's a live example working on fiddle

Upvotes: 0

Jeff Beck
Jeff Beck

Reputation: 3938

You can do it by saving the children first here is a codepen of it working.

http://codepen.io/beckje01/pen/sGLot

var h2 = $('#nameUser');
var elmsToSave = h2.children();

h2.empty();
h2.text('bob');
h2.append(elmsToSave);

As pointed out in the comments this will only work if the text to change is first.

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108500

.contents() returns a collection of nodes, including text nodes. So in your case this would work:

$('#nameUser').contents()​​​​​​​​[0].nodeValue = 'Another name';​​

If you want to get every node except the SPAN, try:

$('#nameUser').contents().filter(function() {
    return this.nodeName != 'SPAN';
}).​each(function(i) {
    // modify each text node
    this.nodeValue = 'name '+i;
});​​​​​

DEMO: http://jsfiddle.net/Vks82/

Upvotes: 4

halilb
halilb

Reputation: 4115

This example may help you to change father element without changing child elements:

var content= $('#nameUser').children();
$('#nameUser').text('Altered Text').append(content);​

Upvotes: 1

Jochem Kuijpers
Jochem Kuijpers

Reputation: 1797

Search for the first textnode in childNodes of the h2 element. Change the value of the textnode.

var element = document.getElementById('nameUser');
element.childNodes[0].nodeValue = 'New String';

..should work. Only for this example, because the first childnode is the textnode you want, you don't have to search for it. Otherwise you do..

Upvotes: 2

gdoron
gdoron

Reputation: 150253

$('#nameUser').contents().each(function() {
    if (this.nodeType == 3) 
        this.data = "The text you want here";
});​

Live DEMO

Upvotes: 1

Related Questions