Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an element by class name, from a known parent element

Tags:

I want to find an element by class name. I know it will appear in a particular parent div, so rather than search the entire dom, I'd like to search only the particular div. I am trying this, but does not seem to be the correct syntax:

var element = $("#parentDiv").(".myClassNameOfInterest"); 

what's the right way to do that?

Thanks

like image 697
user246114 Avatar asked Jun 14 '10 02:06

user246114


People also ask

How do you find the parent element of a class?

Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

What is the difference between parentNode and parentElement?

parentNode gives the parent, while . parentElement gives undefined.

How to find elements by class name in selenium?

The class also contains other alternative methods for locating elements. The Selenium WebDriver library for other programming languages has a similar method for locating elements. For example, the Python library finds elements by class name using the CLASS_NAME constant from its By class.

How to get the closest parent element by class in JavaScript?

Use the closest () method to get the closest parent element by class, e.g. child.closest ('.parent'). The closest () method traverses the Element and its parents until it finds a node that matches the provided selector. Here is the HTML for the examples in this article. And here is the related JavaScript code.

What is getElementsByClassName method in HTML?

GetElementsByClassName () method is used to retrieve a collection or array of all the HTML elements that are child nodes of the element on which this method is called and have the class as mentioned in the parameter of this method.

How to get the child element by its ID in JavaScript?

And here is the related JavaScript code. We got the child element by its id and called the closest () method on it. The closest () method traverses the Element and its parents until it finds a node that matches the provided selector. If the element itself matches the selector, the element is returned.


1 Answers

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest"); 
  • .find() - http://api.jquery.com/find

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv"); 

...which sets the context of the jQuery object to the #parentDiv.

EDIT:

Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

like image 70
user113716 Avatar answered Oct 10 '22 02:10

user113716