最可靠的方法是解析 HTML 并递归搜索第一次出现的文本。然后,检查该文本节点的父节点是否是锚点。
这是我编写的通用函数:
/**
* Searches for the first occurence of str in any text node contained in the given DOM
* @param {jQuery} dom A jQuery object containing your DOM nodes
* @param {String} str The string you want to search for.
* @returns {Object} Returns either null or the text node if str was found.
*/
function searchFirstTextOccurrence(dom, str) {
var foundNode = null;
dom.contents().each(function (idx, node) {
if (node.nodeType == Node.TEXT_NODE) {
if (node.textContent.indexOf(str) !== -1) {
foundNode = node;
// break out of each()
return false;
}
} else if (node.nodeType == Node.ELEMENT_NODE) {
var foundInnerNode = searchFirstTextOccurrence($(node), str);
if (foundInnerNode) {
foundNode = foundInnerNode;
// break out of each()
return false;
}
}
});
return foundNode;
}
您的用例:
→ jsFiddle
var content = "This is<div> dummy <a href='#'>content</a> for my <a href='#'>Search String</a> and</div> here is another Searchx String without an anchor tag";
var searchString = "Search String";
var dom = $("<div>" + content + "</div>");
var firstOccurence = searchFirstTextOccurrence(dom, searchString);
if ($(firstOccurence).closest("a").length > 0) {
console.log("Yep");
} else {
console.log("No");
}