虽然您已经接受了答案,但我想我会花点时间向您展示一种更易于自定义的方法,它允许您查找 - 并检索 - 元素文本中包含的所有子元素(正如您的标题所暗示的那样:“使用 [jQuery] 选择具有 html 实体的 [<div> 元素]”),或者它允许您过滤这些元素中的特定类型的元素(因为您问题的第一行暗示您想要:“我需要选择所有包含 . 的 [<div> 元素]”)。
也就是说,以下内容涵盖了使用纯 JavaScript 的两种情况:
// str: String, the textContent of a given node.
// filterFor: String, the tag-name of an element-type
// for which you wish to search (eg: 'div',
// 'sup' etc).
function hasEntities(str, filterFor) {
// a temporary element to contain the supplied string
// of text:
var temp = document.createElement('div'),
// a variable to hold the child elements of the
// temp element (to be used later):
parsed;
// assigning the text as the innerHTML of the
// created element:
temp.innerHTML = str;
// finding all elements contained within the created-
// element, using the CSS universal selector ('*');
// and converting that collection into an Array, using
// Array.from:
parsed = Array.from( temp.querySelectorAll('*') );
// if a filterFor argument was supplied:
if (filterFor) {
// we first remove all '<', '/' and '>' characters from
// the supplied string, replacing them with an empty-
// String, and then convert it to lower-case:
filterFor = filterFor.replace(/(<|\/|>)+/g, '').toLowerCase();
// here we filter the array of nodes using
// Array.prototype.filter() to discard all elements
// for which the assessment does not return true
// or truthy; and then return that filtered
// array to the calling context:
return parsed.filter(function(n) {
// if the current element of the Array of element
// nodes found within the created-element, in
// lower-case, is equal to the element-type we're
// looking for then we retain that node, otherwise
// it's discarded:
return n.tagName.toLowerCase() === filterFor;
});
}
// if no filterFor argument was supplied then we simply
// return the array of descendant elements:
return parsed;
}
var el = document.querySelector('div'),
parentOfSup = hasEntities(el.textContent, 'sup').length > 0;
console.log(parentOfSup); // returns the <sup> node
console.log(parentOfSup.length); // 1
console.log(parentOfSup.length > 0); // true
function hasEntities(str, filterFor) {
var temp = document.createElement('div'),
parsed;
temp.innerHTML = str;
parsed = Array.from(temp.getElementsByTagName('*'));
if (filterFor) {
filterFor = filterFor.replace(/(<|\/|>)+/g, '').toLowerCase();
return parsed.filter(function(n) {
return n.tagName.toLowerCase() === filterFor;
});
}
return parsed;
}
var el = document.querySelector('div'),
parentOfSup = hasEntities(el.textContent, 'sup').length > 0;
console.log(parentOfSup);
<div>I have a &lt;sup&gt;superscript&lt;/sup&gt;&lt;div&gt;and a child div&lt;/div&gt;!</div>