检查<p>元素是否包含值

时间:2017-02-19 14:34:28

标签: javascript html cordova javascript-events innerhtml

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

例如,如果元素是这样的:<p></p>我希望它返回0,或者假或null或类似的东西,如果它像<p>Hello World</p>那样让我回归真实,或值,或1,或类似的东西。

2 个答案:

答案 0 :(得分:3)

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

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

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

如果您还希望将<p> </p>视为空(请注意那里有空格),您需要处理其中包含空格的文本节点:

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

nodeType 3是一个文本节点。trim修剪字符串中的空格。您可能需要在过时的浏览器上使用polyfill。)

示例:

&#13;
&#13;
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));
}  
&#13;
.as-console-wrapper {
  max-height: 100% !important;
}
&#13;
<p id="ex1"></p>
<p id="ex2"> </p>
<p id="ex3">test</p>
<p id="ex4"><strong>test</strong></p>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您还可以使用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>