JavaScript for WordPress Forums Vanilla JavaScript 1.3.04 – Traversing the DOM

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #16628


    I’m sure I missed something or totally misunderstood, but I don’t get why we’re using variables instead of directly selecting the elements.

    In this lesson, you set up a variable for the H1 and then use that with more variables that traverse to its parent.

    var h1 = document.querySelector( 'h1' ),
        h1ParentEl = h1.parentElement,
        h1ParentNode = h1.parentNode;

    Why aren’t we just selecting it directly? Something like:


    And then wouldn’t you just add the parent traversal? Like:


    I’m a beginner with JavaScript so I probably just don’t comprehend anything yet.

    Zac Gordon

    Hi Bonnie!

    You raise a great question here and it really comes down to coding styles.

    In general the WP coding standards like you to define things in variables before using and if you’re ever going to use something twice you definitely want to assign it as a variable.

    That said, combining it all into one statement is completely valid. As we look at more advanced JS and stuff outside the WP community, like with the different frameworks you may see more of this style of combining calls into one line of code rather than several.

    Hope this helps explain!!!


    Ah, okay. That does help. Thanks!

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.