首页 > 解决方案 > 为什么我的 firstNode.nodeValue 返回 null?

问题描述

我正在尝试将第一个 p 标签拆分为 3 个单独的行并使用 javascript 节点将它们显示在第二个 p 标签中。但我得到一个空的返回值。

Chrome 向我抛出一个运行时错误,说它“无法读取属性 'nodeValue' of null”

有人可以帮助我吗?

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style media="screen">
    .hideOriginal {
      display: none;
    }
  </style>
</head>

<body>
  <p id="oneLine">
    <span>Hi my name is John Doe</span>
    <span>I'm learning web development</span>
    <span>I'm 100 years old.</span>
  </p>

  <p class="lineBreak"></p>

  <input type="button" name="" id="fixLineBreak" value="Line Break">
</body>

<script type="text/javascript">

  const breakLineFunction = () => {
    const spans = document.querySelector("#oneLine");
    document.querySelector("#oneLine").setAttribute("class", "hideOriginal")
    let newLine = "";
    const first = spans.firstChild.firstChild.nodeValue;
    const second = spans.firstChild.nextElementSibling.firstChild.nodeValue;
    const last = spans.lastChild.firstChild.nodeValue;
    const brk = "<br><br>";
    newLine = `${first}${brk}${second}${brk}${last}`;
    document.querySelector(".lineBreak").innerHTML = newLine;
  }

  document.addEventListener("DOMContentLoaded", () => {
    document.querySelector("#fixLineBreak").addEventListener("click", breakLineFunction);
  })

</script>

</html>

标签: javascriptnodes

解决方案


 const breakLineFunction = () => {
    const spans = document.querySelector("#oneLine");
    document.querySelector("#oneLine").setAttribute("class", "hideOriginal")
    let newLine = "";
    const first = spans.firstChild.nodeValue;
    const second = spans.firstChild.nextElementSibling.firstChild.nodeValue;
    const last = spans.lastElementChild.textContent
;
    const brk = "<br><br>";
    newLine = `${first}${brk}${second}${brk}${last}`;
    document.querySelector(".lineBreak").innerHTML = newLine;
  }

  document.addEventListener("DOMContentLoaded", () => {
    document.querySelector("#fixLineBreak").addEventListener("click", breakLineFunction);
  })
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style media="screen">
    .hideOriginal {
      display: none;
    }
  </style>
</head>

<body>
  <p id="oneLine">
    <span>Hi my name is John Doe</span>
    <span>I'm learning web development</span>
    <span>I'm 100 years old.</span>
  </p>

  <p class="lineBreak"></p>

  <input type="button" name="" id="fixLineBreak" value="Line Break">
</body>

</html>


推荐阅读