Javascript Finds An Element

| | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

The jQuery find () method may sound familiar, but don’t confuse it with the JavaScript find () method! Both "find" things, but what they return can be very different. In JavaScript, the find () method can only be called on an array.

Requires a callback function, which is a function passed to a method as an argument, to call later. Finds and returns the first item that meets the requirements described in the callback function.

The jQuery find () method is quite different. Like all jQuery methods, it is called on a selector. Search in this selector and manipulate only the child elements of this selector. This high level of manipulation is useful if you want to modify some elements and not others that are contained in the same parent element.

Using jQuery find ()

We now know jQuery find () is used to select all child elements of a given selector. Check out some code samples to see how to use jQuery find ().

Let’s start simple and add some complexity in the following sections. We can manipulate an element after the page loads to demonstrate how find () works. How about changing the color of some words in the context of a paragraph after the page loads? We’ll start from here:

Every other word will remain the same.

Look at this code and you will notice inside the

a few elements . One of the elements is a child of the

element . The other is a child of the

IR3bnpJdRzIwsq 1CzCQeT4Lf2F4YaVtdHjwqHecFlqkjNYR Oi9DIefQs IX6Kf1Bh0JQQNYqxQG7okIP98RPQ PYHTDhu AOabwfhnwB4rdWRmoMw5WgSDtLIKD5ZU9b4 is HTML <HTDML> We now change the colors of the text to illustrate <code>find ()</code> in action. This is a great step for beginners as we only need to modify one CSS attribute to achieve this. Passing the element <p>as a selector to <code>find ()</code>, we can use jQuery’s <code>css ()</code> method to make the color changes:</p>  <p>When first using <code>find () </code>, we select all the elements  <p>. We use <code>find ()</code> to find all <span> elements that are children of <p>. In this example, it’s just the word blue. We then use the <code>css ()</code> method to change the color to blue. <br></p>  </div>  </div> <p>On the second use of <code>find ()</code>. This time we select the . <br></p> <p>Again, this is just the green word. As for the first line, we use the <code>css ()</code> method to change the color to green. <br></p> <p>Let’s run it and see what happens ! <br> </p> <figure class = X NmmVK1C Z30uO5sa15iVH9aCEO ASkwA4cuqwxOagZqMkO8QpJd AlJeZH2NXXSALKH8lWknoNiwXquCqxMuztLiG CL0FzyoN60rr OR3aktZVCcmRgyHPk7Fd7hsjGON74Pi

Note that the blue and green words were included in a span element without any class or id assigned. We were able to isolate these words again and change their color. As you might have guessed, this is because the main elements of are different.


is the parent of the of the blue word. The is the parent of the containing the word green.

This happened because find () finds the children of the elements used as a selector. Let’s add some complexity and look at an example to-do list.

jQuery find () in a list

In this example, we have a to-do list. We have things to do today, but we also have to buy things from the store to do it. Once we have purchased these items, we can take them off the list and get on with our day! Here is our list:

Here we have our list. We have the

  • ; elements of " Go to Store, " " Take out the Trash " and " Do the dishes " as children of the
  •  9 PKrmYrpttbZVdC MrqVjbqAW3bz5t4QCkiZFYhLIuJqsIhUjTQxC7ipWbdnJOfk1ndFDF EcJuV47VM VtfzQd3vp1JNtWxBuOq8Ku0XjNxp4QrnXybM3veW8Gk6ttETa7fk


    jQuery find () identifies all selector child elements that is passed to it. The method will only handle these child elements and not the parent itself.

    Being able to differentiate the children to select allows us to be general and edit sections whole of a page, or specific and to edit only certain elements of a page age. It is in this flexibility that find () is most useful.

    Learn more about learning jQuery here .

    👻 Read also: what is the best laptop for engineering students?

    Javascript Finds An Element find: Questions

    Finding the index of an item in a list

    5 answers

    Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?


    Answer #1

    >>> ["foo", "bar", "baz"].index("bar")

    Reference: Data Structures > More on Lists

    Caveats follow

    Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can"t remember the last time I used it in anger. It"s been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index follow. It is probably worth initially taking a look at the documentation for it:

    list.index(x[, start[, end]])

    Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

    The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

    Linear time-complexity in list length

    An index call checks every element of the list in order, until it finds a match. If your list is long, and you don"t know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999), because the former only has to search 10 entries, while the latter searches a million:

    >>> import timeit
    >>> timeit.timeit("l.index(999_999)", setup="l = list(range(0, 1_000_000))", number=1000)
    >>> timeit.timeit("l.index(999_999, 999_990, 1_000_000)", setup="l = list(range(0, 1_000_000))", number=1000)

    Only returns the index of the first match to its argument

    A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

    >>> [1, 1].index(1)
    >>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
    [0, 2]
    >>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
    >>> next(g)
    >>> next(g)

    Most places where I once would have used index, I now use a list comprehension or generator expression because they"re more generalizable. So if you"re considering reaching for index, take a look at these excellent Python features.

    Throws if element not present in list

    A call to index results in a ValueError if the item"s not present.

    >>> [1, 1].index(2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: 2 is not in list

    If the item might not be present in the list, you should either

    1. Check for it first with item in my_list (clean, readable approach), or
    2. Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.)


    Answer #2

    One thing that is really helpful in learning Python is to use the interactive help function:

    >>> help(["foo", "bar", "baz"])
    Help on list object:
    class list(object)
     |  index(...)
     |      L.index(value, [start, [stop]]) -> integer -- return first index of value

    which will often lead you to the method you are looking for.


    Answer #3

    The majority of answers explain how to find a single index, but their methods do not return multiple indexes if the item is in the list multiple times. Use enumerate():

    for i, j in enumerate(["foo", "bar", "baz"]):
        if j == "bar":

    The index() function only returns the first occurrence, while enumerate() returns all occurrences.

    As a list comprehension:

    [i for i, j in enumerate(["foo", "bar", "baz"]) if j == "bar"]

    Here"s also another small solution with itertools.count() (which is pretty much the same approach as enumerate):

    from itertools import izip as zip, count # izip for maximum efficiency
    [i for i, j in zip(count(), ["foo", "bar", "baz"]) if j == "bar"]

    This is more efficient for larger lists than using enumerate():

    $ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ["foo", "bar", "baz"]*500) if j == "bar"]"
    10000 loops, best of 3: 174 usec per loop
    $ python -m timeit "[i for i, j in enumerate(["foo", "bar", "baz"]*500) if j == "bar"]"
    10000 loops, best of 3: 196 usec per loop


    InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

    3 answers

    Tried to perform REST GET through python requests with the following code and I got error.

    Code snip:

    import requests
    header = {"Authorization": "Bearer..."}
    url = az_base_url + az_subscription_id + "/resourcegroups/Default-Networking/resources?" + az_api_version
    r = requests.get(url, headers=header)


              InsecurePlatformWarning: A true SSLContext object is not available. 
              This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. 
              For more information, see

    My python version is 2.7.3. I tried to install urllib3 and requests[security] as some other thread suggests, I still got the same error.

    Wonder if anyone can provide some tips?


    Answer #1

    The docs give a fair indicator of what"s required., however requests allow us to skip a few steps:

    You only need to install the security package extras (thanks @admdrew for pointing it out)

    $ pip install requests[security]

    or, install them directly:

    $ pip install pyopenssl ndg-httpsclient pyasn1

    Requests will then automatically inject pyopenssl into urllib3

    If you"re on ubuntu, you may run into trouble installing pyopenssl, you"ll need these dependencies:

    $ apt-get install libffi-dev libssl-dev


    Dynamic instantiation from string name of a class in dynamically imported module?

    3 answers

    In python, I have to instantiate certain class, knowing its name in a string, but this class "lives" in a dynamically imported module. An example follows:

    loader-class script:

    import sys
    class loader:
      def __init__(self, module_name, class_name): # both args are strings
          modul = sys.modules[module_name]
          instance = modul.class_name() # obviously this doesn"t works, here is my main problem!
        except ImportError:
           # manage import error

    some-dynamically-loaded-module script:

    class myName:
      # etc...

    I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...


    Answer #1

    You can use getattr

    getattr(module, class_name)

    to access the class. More complete code:

    module = __import__(module_name)
    class_ = getattr(module, class_name)
    instance = class_()

    As mentioned below, we may use importlib

    import importlib
    module = importlib.import_module(module_name)
    class_ = getattr(module, class_name)
    instance = class_()


    How to get all of the immediate subdirectories in Python

    3 answers

    I"m trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions).

    I"m getting bogged down by trying to get the list of subdirectories.


    Answer #1

    import os
    def get_immediate_subdirectories(a_dir):
        return [name for name in os.listdir(a_dir)
                if os.path.isdir(os.path.join(a_dir, name))]

    We hope this article has helped you to resolve the problem. Apart from Javascript Finds An Element, check other find-related topics.

    Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

    By the way, this material is also available in other languages:

    Carlo Zelotti

    London | 2022-12-01

    find is always a bit confusing 😭 Javascript Finds An Element is not the only problem I encountered. Will use it in my bachelor thesis

    Anna OConnell

    London | 2022-12-01

    Thanks for explaining! I was stuck with Javascript Finds An Element for some hours, finally got it done 🤗. I just hope that will not emerge anymore

    Cornwall Chamberlet

    Rome | 2022-12-01

    I was preparing for my coding interview, thanks for clarifying this - Javascript Finds An Element in Python is not the simplest one. I am just not quite sure it is the best method


    Learn programming in R: courses


    Best Python online courses for 2022


    Best laptop for Fortnite


    Best laptop for Excel


    Best laptop for Solidworks


    Best laptop for Roblox


    Best computer for crypto mining


    Best laptop for Sims 4


    Latest questions


    Common xlabel/ylabel for matplotlib subplots

    12 answers


    How to specify multiple return types using type-hints

    12 answers


    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    12 answers


    Flake8: Ignore specific warning for entire file

    12 answers


    glob exclude pattern

    12 answers


    How to avoid HTTP error 429 (Too Many Requests) python

    12 answers


    Python CSV error: line contains NULL byte

    12 answers


    csv.Error: iterator should return strings, not bytes

    12 answers


    Python | How to copy data from one Excel sheet to another

    Common xlabel/ylabel for matplotlib subplots

    Check if one list is a subset of another in Python


    How to specify multiple return types using type-hints


    Printing words vertically in Python


    Python Extract words from a given string

    Cyclic redundancy check in Python

    Finding mean, median, mode in Python without libraries


    Python add suffix / add prefix to strings in a list

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    Python - Move item to the end of the list

    Python - Print list vertically