.find( selector )Returns: jQuery
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
-
version added: 1.0.find( selector )
-
selector
A string containing a selector expression to match elements against.
-
-
version added: 1.6.find( element )
-
element
An element or a jQuery object to match elements against.
-
Given a jQuery object that represents a set of DOM elements, the .find()
method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find()
and .children()
methods are similar, except that the latter only travels a single level down the DOM tree.
The first signature for the .find()
method accepts a selector expression of the same type that we can pass to the $()
function. The elements will be filtered by testing whether they match this selector; all parts of the selector must lie inside of an element on which .find() is called. The expressions allowed include selectors like > p
which will find all the paragraphs that are children of the elements in the jQuery object.
Consider a page with a basic nested list on it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
If we begin at item II, we can find list items within it:
1 |
|
The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.
Unlike most of the tree traversal methods, the selector expression is required in a call to .find()
. If we need to retrieve all of the descendant elements, we can pass in the universal selector '*'
to accomplish this.
Selector context is implemented with the .find()
method;
therefore, $( "li.item-ii" ).find( "li" )
is equivalent to $( "li", "li.item-ii" )
.
As of jQuery 1.6, we can also filter the selection with a given jQuery collection or element. With the same nested list as above, if we start with:
1 |
|
And then pass this jQuery object to find:
1 |
|
This will return a jQuery collection which contains only the list elements that are descendants of item II.
Similarly, an element may also be passed to find:
1 2 |
|
The result of this call would be a red background on item 1.
Examples:
Starts with all paragraphs and searches for descendant span elements, same as $( "p span" )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Demo:
A selection using a jQuery collection of all span tags. Only spans within p tags are changed to red while others are left blue.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Demo:
Add spans around each word then add a hover and italicize words with the letter t.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
Demo:
Typically in JavaScript I do something like the below to verify an element does exist:
if (document.getElementById('lblUpdateStatus')) {
$("#lblUpdateStatus").text("");
}
But, using jQuery — how can I do the same type of thing?
asked Jun 22, 2009 at 13:03
Toran BillupsToran Billups
27.1k39 gold badges154 silver badges268 bronze badges
1
$
returns an array of matching elements, so check the length property and you’re good to go
if ($('#lblUpdateStatus').length) {
$("#lblUpdateStatus").text("");
}
answered Jun 22, 2009 at 13:05
The get method returns the matched DOM elements:
if($("#lblUpdateStatus").get(0)){
$("#lblUpdateStatus").click(function () { ... });
}
but I am not sure if it is a fast method.
answered Jun 22, 2009 at 13:08
Tony L.Tony L.
7,9885 gold badges24 silver badges28 bronze badges
The thing is that the jQuery will only do the requested action if the element exists :-),
so you only need:
$("#lblUpdateStatus").text("");
answered Jun 22, 2009 at 13:04
bangbang
4,8821 gold badge24 silver badges28 bronze badges
I see no reason to use jQuery just for the sake of it. the $('#lblUpdateStatus')
will basically go straight to document.getElementById('lblUpdateStatus')
, as the selector has an anchor in it, so you’re not really gaining anything. Also, for just checking if the DOM object exists, wrapping it in a jQuery object will create quite a lot of overhead.
On the other hand, if just changing the text property of the object is what you want to do, you don’t need to check for its existence if you use jQuery.
if (document.getElementById('lblUpdateStatus')) {
$("#lblUpdateStatus").text("");
}
will do the exact same thing as having just
$("#lblUpdateStatus").text("");
answered Jun 22, 2009 at 13:08
Tomas AschanTomas Aschan
58k56 gold badges240 silver badges400 bronze badges
3
From jQuery 1.4 onwards you can use $.contains()
.
var test = $("<div>");
$.contains(window.document, test[0]); // false
$("body").append(test);
$.contains(window.document, test[0]); // true
answered Oct 17, 2012 at 9:44
Ian MackinnonIan Mackinnon
13.2k13 gold badges51 silver badges66 bronze badges
1
I wrote a post about that on my blog
if ( $('#element_id').length > 0 )
console.log('the element with element_id exists in the DOM');
Jeff Atwood
63.2k48 gold badges149 silver badges153 bronze badges
answered Jul 8, 2009 at 10:31
stoimenstoimen
5523 silver badges7 bronze badges
1
If HTML string can be passed into $()
, you can use parent.length
:
$('<div>').length // 1, but it not exist on page
but
$('<div>').parent().length // 0
answered Aug 2, 2012 at 7:40
vitaletsvitalets
4,5651 gold badge35 silver badges35 bronze badges
I would use this. Calculate the lenght of the node list:
document.querySelectorAll('#lblUpdateStatus').length
answered Jul 13, 2020 at 19:51
На практике приходится очень часто проверять существует ли элемент на веб-странице или нет.
Например, задача может быть следующей:
если на странице есть блок div с атрибутом id, то нужно выполнить какие-то действия с элементами, которые в нем находятся.
Такую проверку очень важно производить. Если в скрипте будет запрашиваться элемент, которого нет на странице, то будет ошибка. Скорее всего, вы знаете, насколько могут быть опасны ошибки в Javascript, весь код который расположен ниже, может просто не обрабатываться.
Поэтому производить проверку существования элемента — это очень важный момент.
Хочу рассказать о способе, как это можно сделать с помощью библиотеки Jquery.
Вот пример:
$(«#mydiv»).length – это выражение будет возвращать true, когда скрипту удалось найти элемент и false в противном случае. Именно этот принцип работы и позволяет выполнить необходимую проверку.
Если у вас появляется окно такого вида, значит, все работает нормально.
Все мои уроки по Javascript здесь.
- Комментарии
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
There are two ways to check whether an element in the HTML document exists or not using jQuery.
Approach 1: Using the length property in jQuery. If the element exists, then the length property will return the total count of the matched elements with the specified selector. In JavaScript, everything is either a truthy or a falsy value, thus if the length is 0 then it evaluates to false, everything else is true.
There is one div element defined in the following example and there are two buttons, which on click check the existence of two separate divs. If the first button is clicked, an alert message is displayed which states that “div 1 exists” since a div element with an id of div1 is present in the HTML markup. However, if the second button is clicked, an alert message is still shown but it states that “div 2 does not exist” since a div element with an id of div2 is absent.
Example:
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
script
src
=
</
script
>
<
title
>Check whether an element exists or not using jQuery</
title
>
<
style
>
body {
text-align: center;
}
h1 {
color: green;
font-size: 2.5rem;
}
div {
font-weight: bold;
font-size: 1.5rem;
}
button {
cursor: pointer;
margin-top: 2rem;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksforGeeks</
h1
>
<
div
id
=
"div1"
>This is div with id div1</
div
>
<
button
id
=
"div-1-check-btn"
>
Click to check if div 1 exists
</
button
>
<
button
id
=
"div-2-check-btn"
>
Click to check if div 2 exists
</
button
>
<
script
type
=
"text/javascript"
>
$(document).ready(function () {
$("#div-1-check-btn").click(function () {
if ($("#div1").length) {
alert("Div 1 exists");
} else {
alert("Div 1 does not exist");
}
});
$("#div-2-check-btn").click(function () {
if ($("#div2").length) {
alert("Div 2 exists");
} else {
alert("Div 2 does not exist");
}
});
});
</
script
>
</
body
>
</
html
>
Output:
Approach 2: Using a jQuery plugin with methods. This approach is quite similar to the first approach due to the fact that it also uses the length property in jQuery but the difference is that a user-defined method exists() is created from the plugin using the same logic of truthy and falsy values of length as discussed in the previous technique.
There is one div element defined in the following example and there are two buttons, which on click check the existence of two separate divs. If the first button is clicked, an alert message is displayed which states that “div 1 does not exist” since a div element with an id of div1 is absent in the HTML markup. However, if the second button is clicked, an alert message is still shown but it states that “div2 exists” since a div element with an id of div2 is present.
Example:
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
script
src
=
</
script
>
<
title
>Check whether an element exists or not using jQuery</
title
>
<
style
>
body {
text-align: center;
}
h1 {
color: green;
font-size: 2.5rem;
}
div {
font-weight: bold;
font-size: 1.5rem;
}
button {
cursor: pointer;
margin-top: 2rem;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksforGeeks</
h1
>
<
div
id
=
"div2"
>This is div with id div2</
div
>
<
button
id
=
"div-1-check-btn"
>
Click to check if div 1 exists
</
button
>
<
button
id
=
"div-2-check-btn"
>
Click to check if div 2 exists
</
button
>
<
script
type
=
"text/javascript"
>
$(document).ready(function () {
jQuery.fn.exists = function () {
return this.length > 0;
};
$("#div-1-check-btn").click(function () {
if ($("#div1").exists()) {
alert("Div 1 exists");
} else {
alert("Div 1 does not exist");
}
});
$("#div-2-check-btn").click(function () {
if ($("#div2").exists()) {
alert("Div 2 exists");
} else {
alert("Div 2 does not exist");
}
});
});
</
script
>
</
body
>
</
html
>
Output:
Last Updated :
12 Feb, 2022
Like Article
Save Article
This post will discuss how to check whether an element exists in DOM or not with jQuery.
1. Using $(selector).length
To check if an element is present in DOM with jQuery, you can use the selectors. They return one or more matching elements within a document. Then check the .length
property or call the .size()
method to get the size of the jQuery object array returned.
$(document).ready(function() { if ($(«#name»).length) { alert(«The element exists»); } else { alert(«The element does not exist»); } }); |
HTML
<label>Email address: <input type=«email» id=«name» placeholder=«Enter email»></label> |
Edit in JSFiddle
2. Using $(selector)[0]
If the element is present in DOM, then the first item in the jQuery object array would be defined. So, you can also do like:
jQuery
$(document).ready(function() { if ($(«#name»)[0]) { alert(«The element exists»); } else { alert(«The element does not exist»); } }); |
HTML
<label>Email address: <input type=«email» id=«name» placeholder=«Enter email»></label> |
Edit in JSFiddle
That’s all about determining whether an element exists in DOM or not with jQuery.
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding