我有一个div,这个div可以(或不能)将html元素作为子元素。使用我的javascript,我需要找到此div中所有出现的单词,除了<a>
标记中的单词。
例如:
<div id="dictionable">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<br/><br/>
<a href="#lorem">lorem</a>
<br/><br/>
<p>lorem</p>
</div>
我尝试使用我的超低功能构建一个正则表达式,失败了。 所以我用Google搜索并发现了这个:
var pattern = new RegExp('(lorem)(?![^<]*>|[^<>]*</)', 'gim');
这个正则表达式发现&#34; lorem&#34;但不是每个标签。 我只需要排除A标签。
有人可以帮助我吗?
答案 0 :(得分:6)
没有正则表达式。绝对没有正则表达式。新加坡国立大学医院,嗯。不。
var copy = document.getElementById('dictionable').cloneNode(true),
links = copy.getElementsByTagName('a'), l = links.length, i;
for( i=l-1; i>=0; i--) {
// always work in reverse order when deleting stuff, it's safer!
links[i].parentNode.removeChild(links[i]);
}
var result = copy.textContent || copy.innerText;
轰!
答案 1 :(得分:4)
使用jquery太简单了
var $dictionable = $("#dictionable").clone();
$dictionable.find('a').remove();//This will remove all <a> tag
$dictionable.text();//This will give all text
答案 2 :(得分:0)
由于元素中的所有内容都被视为元素,因此您可以简单地遍历div的子元素。
当然,由于其验证,它不是最短的解决方案,但它应该相对较快。
var d = document.getElementById('dictionable');
var textcontent = '';
for (node in d.childNodes) {
// accept only element (1), text (3) and non-link element
if ((d.childNodes[node].nodeType != 1 &&
d.childNodes[node].nodeType != 3) ||
d.childNodes[node].nodeName == 'A')
continue;
textcontent = textcontent+d.childNodes[node].textContent
}
这是你甚至可以在循环中设置搜索并将结果缩小到单个元素级别。