How to only change the text in a DOM element witho

2020-04-02 18:38发布

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.

7条回答
Emotional °昔
2楼-- · 2020-04-02 19:16

Another short jQuery solution:

$("h1").contents().first().replaceWith("new text");

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

查看更多
登录 后发表回答