jquery - find element that only has text and not any other html tag

假如想象 提交于 2019-12-10 13:09:49

问题


I need to check with jquery that a anchor element only has text in it and not any other tag (img, b) or any thing else.

<a href="">TV</a>

Should be found, but :

<a href=""><img /></a>

or:

<a href=""><span>TV</span></a>

or any other HTML tag, shouldn't be found.

How do i do this?

Thanks in advance.


回答1:


We can use the filter() function to remove elements which have children (checked using the children() method).

var emptyAs = $('a').filter(function () {
    return $(this).children().length == 0;
});

You could also use the :not() selector combined with the :has() selector;

var moreEmptyAs = $('a:not(:has(*))');

You can see both of these working in the following JSFiddle; http://jsfiddle.net/JD67U/




回答2:


You can try .text() this escapes only the text and eliminates every HTML Code.

var pureText=$('a').text();


来源:https://stackoverflow.com/questions/8518982/jquery-find-element-that-only-has-text-and-not-any-other-html-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!