简体   繁体   中英

How can I remove the tag's text with Javascript, only the text not tag

HTML:

<h2>
Available courses
    <span>Available courses</span>
</h2>   

SCRIPTS:

var textCon1 = document.querySelector("#frontpage-course-list h2");
var textCon2 = document.querySelector("#frontpage-course-list h2").innerHTML;
var createSpan = document.createElement("span");
createSpan.innerHTML = textCon2;
textCon2.appendChild(createSpan);
textCon1.innerHTML="";

Here I am trying to remove the text available in h2 tag, but it removes everything available in h2 tag. I want to keep span tag with text.

simple add this line, demo

textCon1.childNodes[0].textContent = "";

it will replace the first text-node with empty text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM