Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 320
Ovi Avatar asked Dec 15 '11 10:12

Ovi


People also ask

How to find element by text in jQuery?

This can be done using the jQuery contains selector to select elements that contain the string. Depending on the element, the matching text can appear directly within or within a descendant of the selected element. The :contains() selector in jQuery is used to select elements containing the specified string.

How do I get just the text from HTML in jQuery?

You could use $('. gettext'). text(); in jQuery.

How to select element content in jQuery?

jQuery :contains() Selector The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

What is not() in jQuery?

The not() is an inbuilt function in jQuery which is just opposite to the filter() method. This function will return all the element which is not matched with the selected element with the particular “id” or “class”. The selector is the selected element which is not to be selected.


1 Answers

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/

like image 184
Matt Avatar answered Nov 15 '22 06:11

Matt