Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only change the text in a DOM element without replacing any child elements

Hi I have a simple html structure

<h1>Title text <span>inner text</span></h1>

What I want is to replace only the text (Title text) without disturb the <span> text. Is this possible?

I don't want to add any other dom element, I would like to keep that structure. I been doing this of course.

$("h1").text("new text");

But you can guess... will replace all the innert text and the span text element as well.

Possible solution: I was thinking in copy in a variable the text of the span and then concatenate it with the new <h1> text, But I think maybe exist a better and clean way to do it.

like image 547
ncubica Avatar asked Mar 25 '13 19:03

ncubica


People also ask

How do I edit text inside a div?

Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content.

Can DOM objects be modified?

The Document Object Model (DOM) is a programming interface for HTML web pages. Scripting languages, like JavaScript, can access and manipulate the DOM to alter the display of a web page. In this guide, you learn about the methods and properties you can use to modify the DOM by adding and removing element nodes.

How can we change text element?

Use the textContent property to change the text of an element, e.g. element. textContent = 'New text' . The textContent property will set the text of the element to the provided string, replacing any of the existing content.


2 Answers

Using jQuery.contents() you can replace the nodeValue similar to this:

$("h1").contents()[0].nodeValue = "new text ";

DEMO using jQuery.contents() to replace a text node


like image 176
Nope Avatar answered Sep 29 '22 00:09

Nope


$("h1").each(function() {
    var textNode = document.createTextNode("new text");
    this.replaceChild(textNode, this.firstChild);
});

DEMO: http://jsfiddle.net/FvbJa/

like image 34
VisioN Avatar answered Sep 29 '22 02:09

VisioN