如何使用Javascript删除标记文本,只删除文本标记

时间:2016-03-07 07:00:21

标签: javascript

HTML:

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="";

脚本:

var results=[
    {
        "title": "Sample Post",
        "content": {
          "brief": "<p>This is my brief content</p>",
          "extended": "<p>Here is the detail</p>"
        }
      },
    {
        "title": "Post 6",
        "content": {
          "brief": "<p>Brief for Post 6</p>",
          "extended": "<p>Full description for Post 6</p>"
        }
      },
      {
        "title": "Post 7",
        "content": {
          "brief": "<p>Brief for Post 7</p>",
          "extended": "<p>Full description for Post 7</p>"
        }
      },
      {
        "title": "Post 8",
        "content": {
          "brief": "<p>Brief for Post 8</p>",
          "extended": "<p>Full description for Post 8</p>"
        }
      },
    {
        "title": "Post 1",
        "content": {
          "brief": "<p>Brief for post 1</p>",
          "extended": "<p>Full description&nbsp;for post 1</p>"
        }
      },
      {
        "title": "Post 2",
        "content": {
          "brief": "<p>Brief&nbsp;for post 2</p>",
          "extended": "<p>Full description&nbsp;for post 2</p>"
        }
      },
      {
        "title": "Post 222",
        "content": {
          "brief": "<p>Brief&nbsp;for post 3</p>",
          "extended": "<p>Full description&nbsp;for post 3</p>"
        }
      },
    {
        "title": "Post 113",
        "content": {
          "brief": "<p>Brief&nbsp;for post 3</p>",
          "extended": "<p>Full description&nbsp;for post 3</p>"
        }
      },
    {
        "title": "Post 223",
        "content": {
          "brief": "<p>Brief&nbsp;for post 3</p>",
          "extended": "<p>Full description&nbsp;for post 3</p>"
        }
      }
];

这里我试图删除h2标签中可用的文本,但它删除了h2标签中的所有可用内容。我想用文本保留span标记。

1 个答案:

答案 0 :(得分:2)

简单地添加这一行demo

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

它将用空文本替换第一个text-node