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
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.
parentNode gives the parent, while . parentElement gives undefined.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With