查找不在<a> Tags?

时间:2019-04-24 14:12:22

标签: javascript jquery

I'm writing a JavaScript that goes through an html document and finds all instances of a keyword that are NOT links -- not within an <a> tag. For example, let's take the following HTML and I'm looking for the keyword "laptops."

<p>I love laptops so much and these are <a href="mylink">some of my <i>favorite laptops</i></a>. Don't you love laptops also?</p>

So I need a way to return instances 1 and 3 here, but not number 2, because it is within a link. I'm not sure if the right way to do this is with a Regex (I can't figure out the right one for this) or iterating through the DOM or something. I can use either JQuery or straight JS.

1 个答案:

答案 0 :(得分:3)

假设您想要包含“笔记本电脑”的元素列表,这可以帮助您入门:

|id|platform|sites  |path |date
|1 |0       |1,2,3  |//ab |1/2/2019
|2 |0       |1,2    |//ab |1/2/2019
|3 |0       |1,2,3,4|//ab |1/2/2019
|4 |0       |2,3,1  |//ab |1/2/2019
let elements = [...document.querySelectorAll('*')]
    .filter(e =>
        !e.closest('A') &&
        [...e.childNodes].some(c =>
            c.nodeType === 3 && c.textContent.match(/\blaptops?\b/i)));

elements.forEach(e => e.style.border = '1px solid black');
* {padding: 5px;}