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条回答
▲ chillily
2楼-- · 2020-04-02 18:51

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


查看更多
我命由我不由天
3楼-- · 2020-04-02 18:52

This is gonna work without jquery:

$title = documento.querySelector('your h1 element');
$title.firstChild.nodeValue = 'New Title text';
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-04-02 19:04
const ChgBtn = document.querySelector('#change-title')
const title = document.querySelector('#page-title')

ChgBtn.addEventListener('click', (event) => {
  if (title.innerHTML === 'job') {
    title.innerHTML = 'better job'
    event.target.innerHTML = 'Change title back'
  }
  else if (title.innerHTML === 'better job') {
    title.innerHTML = 'job'
    event.target.innerHTML = 'Change Title'
  }
  else {
    console.error('Wrong')
  }
})
查看更多
Ridiculous、
5楼-- · 2020-04-02 19:10

I found this question which might be useful.

you can get the child element by doing this:

var h1_elt = document.getElementById(h1_elt_id);
var span = h1_elt.getElementsByTagName("span");

You can then use the spans innerHTML as part of the h1 elements innerHTML, i.e.: h1_elt.innerHTML = "new text "+span.innerHTML+""

The only thing you would need to change about your HTML is to give the h1 element an id attribute, then use that in place of h1_elt_id.

查看更多
Evening l夕情丶
6楼-- · 2020-04-02 19:12

The following will work.

var h1 = document.getElementById("h1"),
    children = Array.prototype.slice.call(h1.children),
    newText = document.createTextNode("Hello. ");

h1.innerHTML = "";
h1.appendChild(newText);

while(children) {
    h1.appendChild(children.shift());
}

http://jsfiddle.net/TFYmv/

Basically what you're doing is taking a picture of all the children in a specific element, changing the element completely, then re-appending all the previous children back onto the parent element using the picture we took.

查看更多
该账号已被封号
7楼-- · 2020-04-02 19:16
$("h1").each(function() {
    var textNode = document.createTextNode("new text");
    this.replaceChild(textNode, this.firstChild);
});

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

查看更多
登录 后发表回答