As the subject asks, I’m wondering when or why using .parent() would be useful, as opposed to just targeting the desired target element directly?
Say I have, as a quick and ugly example, not using legit tags because it’s being interpreted by the forum software…
… and I want to turn the menuBar’s background blue…
Why would you use
instead of using
What kind of scenarios would the former be a better option than the latter?
Thanks for your time
event object that references the object you bound to. So, if you give
#menuItem1 a click handler, that’s what the event object will refer to.
console.log(event.target); // <div id="menuItem1"></div>
event object also references the parent (and the parent’s parent, and the parent’s parent’s parent, et cetera…). In your case, that parent will always be the same thing since you’re looking at a menu entry in a menubar. But what if that item had been generated dynamically from an AJAX call? The parent isn’t necessarily something you’ve already defined in your code, so you might have to reference it based on what the user clicks.
Another point about what’s defined in code, picking out DOM elements can be an expensive operation. If you’re going to reference the same object more than once, it’s best to cache that reference for use later.
var $menuItem1 = $('#menuItem1');
parent() on the element you’ve already got in memory.
As for forum formatting, make use of the backtick (`) key. In US keyboards, it’s just to the left of the 1 in the top row. See this post for details.
Not all elements in the DOM have/need class names.
Consider situations where you are part of a project and not in control of the HTML structure/class naming. You can work out a selector to a particular element, but what you really need is something along its chain of ancestors, which do not have classes/IDs assigned.
You can select the element that does have the selector, then use other DOM traversal methods to access the one you really want.
The downside to this is that you are relying on the page structure never changing. And, if it is outside of your control, chances are very strong it will! If it does, your code breaks. So you’d want to find a better way to work this out, but that’s an example of when DOM traversal may be needed.
Yes, working with 3rd party libraries which generate HTML that you need to modify, but which do not provide hooks/callbacks to do so is a very good example of code/HTML outside your control.
Hey thank you for the explanations!
A bit of that goes over my head, still, at this point, but I think I understood the gist of it.