我有一个函数matchTagAndText,正如名称所说,接受2个参数的选择器和文本,并检查是否有任何匹配的元素具有给定的文本.它是这样的:
function matchTagAndText(sel,txt) { var elements = document.querySelectorAll(sel); return Array.prototype.filter.call(elements,function(element){ return RegExp(txt,'i').test(element.textContent); }); }
现在我试图选择一个包含文本’Lorem ipsum’的td元素,但我无法这样做.
我的HTML:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Frames</title> </head> <body> <td colspan="2" class="font-description"> Lorem ipsum dolor sit amet,consectetur adipisicing elit. Tempora nulla iste,quae necessitatibus. Impedit mollitia delectus eum voluptas ullam! Perspiciatis in dolorem blanditiis dolores mollitia sint nostrum sunt veniam est! </td> </body> </html>
var el = matchTagAndText('td.font-description','Lorem ipsum');
但是这会返回一个空数组.我的功能出了什么问题?
实例:
function matchTagAndText(sel,'i').test(element.textContent); }); } var el = matchTagAndText('td.font-description','Lorem ipsum'); console.log(el);
<td colspan="2" class="font-description"> Lorem ipsum dolor sit amet,quae necessitatibus. Impedit mollitia delectus eum voluptas ullam! Perspiciatis in dolorem blanditiis dolores mollitia sint nostrum sunt veniam est! </td>
解决方法
有趣的是,问题是您的标记无效:您没有周围的tr或表.如果你修复它,它的工作原理:
function matchTagAndText(sel,'Lorem ipsum'); console.log(el);
<table> <tr> <td colspan="2" class="font-description"> Lorem ipsum dolor sit amet,quae necessitatibus. Impedit mollitia delectus eum voluptas ullam! Perspiciatis in dolorem blanditiis dolores mollitia sint nostrum sunt veniam est! </td> </tr> </table>
如果我们使用Chrome的devtools检查您的示例,我们可以看到,在尝试使HTML有效时,它只是完全剥离了您的td标记及其关联的类,因此您的选择器不匹配任何内容: