检查 <p> 元素中是否有值

Check If a <p> element has a value in it or not

我想检查 <p> 元素中是否包含文本,使用纯 Javascript.

例如,如果元素是这样的:<p></p> 我希望它是 return 我 0,或 false 或 null 或类似的东西,如果它是这样的 <p>Hello World</p> 到 return 我是真的,或者值,或者 1,或者类似的东西。

一旦您引用了 p 元素(来自 getElementByIdquerySelector 或其他),您可以查看它是否 完全 像这样空着:

if (!theElement.firstChild) {
    // It's empty
}

(或theElement.childNodes.length == 0.)

如果你也希望<p> </p>被认为是空的(注意那里有一个space),你需要处理其中带有白色space的文本节点:

if (!theElement.firstChild ||
    (theElement.firstChild.nodeType === 3 &&
     theElement.firstChild.nodeValue.trim() === ""
    )
   ) {
    // It's empty
}

nodeType 3 是一个文本节点。trim 从字符串中去除白色 space。您可能需要在过时的浏览器上使用 polyfill。)

示例:

test("ex1");
test("ex2");
test("ex3");
test("ex4");

function simpleEmpty(theElement) {
  return !theElement.firstChild;
}

function emptyHandlingWhitespace(theElement) {
  return !theElement.firstChild ||
         (theElement.firstChild.nodeType === 3 && theElement.firstChild.nodeValue.trim() === "");
}

function test(id) {
  var theElement = document.getElementById(id);
  console.log(id, simpleEmpty(theElement), emptyHandlingWhitespace(theElement));
}  
.as-console-wrapper {
  max-height: 100% !important;
}
<p id="ex1"></p>
<p id="ex2"> </p>
<p id="ex3">test</p>
<p id="ex4"><strong>test</strong></p>

您也可以使用 innerHTML 属性:

function checkIfContainsText(el) {
  return el.innerHTML === '' ? false : true;
}

console.log(checkIfContainsText(document.getElementById('p1')));
console.log(checkIfContainsText(document.getElementById('p2')))
<p id="p1"></p>
<p id="p2">aaa</p>