在JavaScript/jQuery中,检测一个div元素是否包含特定文本(不包括其子元素的文本)是一个常见的需求。这需要获取元素自身的文本内容,而排除其子元素中的文本。
function hasDirectText(element, text) {
// 获取所有子节点
const childNodes = element.childNodes;
let hasText = false;
// 遍历子节点
for (let i = 0; i < childNodes.length; i++) {
const node = childNodes[i];
// 检查是否是文本节点且不为空
if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') {
if (text === undefined) {
// 如果未指定具体文本,只要有文本内容就返回true
hasText = true;
break;
} else if (node.textContent.includes(text)) {
// 如果指定了文本,检查是否包含
hasText = true;
break;
}
}
}
return hasText;
}
// 使用示例
const div = document.getElementById('myDiv');
console.log(hasDirectText(div)); // 检查是否有任何直接文本
console.log(hasDirectText(div, '特定文本')); // 检查是否包含特定文本
$.fn.hasDirectText = function(text) {
let hasText = false;
this.each(function() {
$(this).contents().each(function() {
if (this.nodeType === Node.TEXT_NODE && $.trim(this.textContent) !== '') {
if (text === undefined) {
hasText = true;
return false; // 退出循环
} else if (this.textContent.includes(text)) {
hasText = true;
return false; // 退出循环
}
}
});
if (hasText) {
return false; // 退出外部循环
}
});
return hasText;
};
// 使用示例
const hasText = $('#myDiv').hasDirectText();
const hasSpecificText = $('#myDiv').hasDirectText('特定文本');
.trim()
或$.trim()
的调用Q: 为什么直接使用text()或innerText不能达到这个目的?
A: 因为这些方法会递归获取所有子元素的文本内容,无法区分是当前元素的文本还是子元素的文本。
Q: 如何同时检查文本内容和排除特定子元素?
A: 可以修改上述方法,在遍历子节点时跳过特定子元素:
function hasDirectTextExcluding(element, text, excludeSelector) {
const childNodes = element.childNodes;
let hasText = false;
for (let i = 0; i < childNodes.length; i++) {
const node = childNodes[i];
// 跳过匹配排除选择器的元素
if (node.nodeType === Node.ELEMENT_NODE && node.matches(excludeSelector)) {
continue;
}
if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') {
if (text === undefined || node.textContent.includes(text)) {
hasText = true;
break;
}
}
}
return hasText;
}