为什么我的firstNode.nodeValue返回null



我正试图将第一个p标记拆分为3行&使用javascript节点在第二个p标记中显示它们。但我得到的返回值为null。

Chrome向我抛出一个运行时错误,说它"无法读取null"的属性"nodeValue">

有人能帮我吗?

<!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>

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>

最新更新