How do I select elements when I already have a DOM element?
jQuery Interview Questions and Answers
(Continued from previous question...)
How do I select elements when I already have a DOM element?
If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object.
var myDomElement = document.getElementById('foo'); // a plain DOM element
$(myDomElement).find('a'); // finds all anchors inside the DOM element
Many people try to concatenate a DOM element or jQuery object with a CSS selector, like so:
$(myDomElement + '.bar'); // WRONG! equivalent to $("[object HTMLElement].bar")
This is wrong. You cannot concatenate strings to objects.
(Continued on next question...)
Other Interview Questions
|