Why do modern JavaScript Frameworks discourage direct interaction with the DOM

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite
2












In dealing with JS frameworks like AngularJS, Angular, and React, I've observed that directly interacting with the DOM is discouraged, and can often lead to bugs, if you ignore the warnings. When I say "interacting with the DOM" I mean using document.getElementById('myElement') and similar methods to do some manipulation or read values from the document.



My question is essentially Why?. Is this a virtual DOM problem, where React (for example) isn't tracking the actual DOM, and therefore will be caught off guard if you make a change "on your own" without notifying React and subsequently updating the virtual DOM? Would Angular have the same problem in such a case?



If someone has knowledge of only a specific framework, I would be very interested to read the answer to my question even if it is not generalized. Obviously, I'm going to go google this some more, but I didn't see a similar question here yet, so I figured I'd post for posterity. Thanks in advance for any insights!










share|improve this question

















  • 2




    whats_so_wrong_with_direct_dom_manipulation ?
    – HDJEMAI
    5 hours ago






  • 1




    I don't know how relevant the Model-View-* architectures are here, but essentially think of the DOM tree as the view - you do not manipulate the view directly from anything outside of it. (And given that these frameworks abstract the view itself it's safe to assume you don't write any of your own view code either.)
    – BoltClock♦
    4 hours ago















up vote
6
down vote

favorite
2












In dealing with JS frameworks like AngularJS, Angular, and React, I've observed that directly interacting with the DOM is discouraged, and can often lead to bugs, if you ignore the warnings. When I say "interacting with the DOM" I mean using document.getElementById('myElement') and similar methods to do some manipulation or read values from the document.



My question is essentially Why?. Is this a virtual DOM problem, where React (for example) isn't tracking the actual DOM, and therefore will be caught off guard if you make a change "on your own" without notifying React and subsequently updating the virtual DOM? Would Angular have the same problem in such a case?



If someone has knowledge of only a specific framework, I would be very interested to read the answer to my question even if it is not generalized. Obviously, I'm going to go google this some more, but I didn't see a similar question here yet, so I figured I'd post for posterity. Thanks in advance for any insights!










share|improve this question

















  • 2




    whats_so_wrong_with_direct_dom_manipulation ?
    – HDJEMAI
    5 hours ago






  • 1




    I don't know how relevant the Model-View-* architectures are here, but essentially think of the DOM tree as the view - you do not manipulate the view directly from anything outside of it. (And given that these frameworks abstract the view itself it's safe to assume you don't write any of your own view code either.)
    – BoltClock♦
    4 hours ago













up vote
6
down vote

favorite
2









up vote
6
down vote

favorite
2






2





In dealing with JS frameworks like AngularJS, Angular, and React, I've observed that directly interacting with the DOM is discouraged, and can often lead to bugs, if you ignore the warnings. When I say "interacting with the DOM" I mean using document.getElementById('myElement') and similar methods to do some manipulation or read values from the document.



My question is essentially Why?. Is this a virtual DOM problem, where React (for example) isn't tracking the actual DOM, and therefore will be caught off guard if you make a change "on your own" without notifying React and subsequently updating the virtual DOM? Would Angular have the same problem in such a case?



If someone has knowledge of only a specific framework, I would be very interested to read the answer to my question even if it is not generalized. Obviously, I'm going to go google this some more, but I didn't see a similar question here yet, so I figured I'd post for posterity. Thanks in advance for any insights!










share|improve this question













In dealing with JS frameworks like AngularJS, Angular, and React, I've observed that directly interacting with the DOM is discouraged, and can often lead to bugs, if you ignore the warnings. When I say "interacting with the DOM" I mean using document.getElementById('myElement') and similar methods to do some manipulation or read values from the document.



My question is essentially Why?. Is this a virtual DOM problem, where React (for example) isn't tracking the actual DOM, and therefore will be caught off guard if you make a change "on your own" without notifying React and subsequently updating the virtual DOM? Would Angular have the same problem in such a case?



If someone has knowledge of only a specific framework, I would be very interested to read the answer to my question even if it is not generalized. Obviously, I'm going to go google this some more, but I didn't see a similar question here yet, so I figured I'd post for posterity. Thanks in advance for any insights!







javascript angular reactjs dom web-frameworks






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 5 hours ago









Ben Steward

579110




579110







  • 2




    whats_so_wrong_with_direct_dom_manipulation ?
    – HDJEMAI
    5 hours ago






  • 1




    I don't know how relevant the Model-View-* architectures are here, but essentially think of the DOM tree as the view - you do not manipulate the view directly from anything outside of it. (And given that these frameworks abstract the view itself it's safe to assume you don't write any of your own view code either.)
    – BoltClock♦
    4 hours ago













  • 2




    whats_so_wrong_with_direct_dom_manipulation ?
    – HDJEMAI
    5 hours ago






  • 1




    I don't know how relevant the Model-View-* architectures are here, but essentially think of the DOM tree as the view - you do not manipulate the view directly from anything outside of it. (And given that these frameworks abstract the view itself it's safe to assume you don't write any of your own view code either.)
    – BoltClock♦
    4 hours ago








2




2




whats_so_wrong_with_direct_dom_manipulation ?
– HDJEMAI
5 hours ago




whats_so_wrong_with_direct_dom_manipulation ?
– HDJEMAI
5 hours ago




1




1




I don't know how relevant the Model-View-* architectures are here, but essentially think of the DOM tree as the view - you do not manipulate the view directly from anything outside of it. (And given that these frameworks abstract the view itself it's safe to assume you don't write any of your own view code either.)
– BoltClock♦
4 hours ago





I don't know how relevant the Model-View-* architectures are here, but essentially think of the DOM tree as the view - you do not manipulate the view directly from anything outside of it. (And given that these frameworks abstract the view itself it's safe to assume you don't write any of your own view code either.)
– BoltClock♦
4 hours ago













2 Answers
2






active

oldest

votes

















up vote
4
down vote













@HDJEMAI linked to this article which I'll repeat, as it's good advice: https://www.reddit.com/r/javascript/comments/6btma7/whats_so_wrong_with_direct_dom_manipulation/



I'll expand on some of those reasons below:



  • Modern frameworks like Angular and React are designed to hide the DOM because they want to abstract the DOM away. By using the DOM directly you break the abstraction and make your code brittle to changes introduced in the framework.


  • There are many reasons to want to abstract-away the DOM, and the Reddit page linked-to mostly focuses on "state management" because your framework (Angular, React, etc) will likely make assumptions about the DOM's state that will be broken if you manipulate the DOM directly, for example:



    function this_is_your_code() 

    tell_angular_to_make_my_sidebar_500px_wide();

    document.getElementById('mysidebar').style.width = 700px;

    var sidebar_width = ask_angular_for_sidebar_width();
    console.log( sidebar_width ); // will print "500px"




  • Another reason to abstract away the DOM is to ensure your code works with non-traditional DOMs besides the typical web-browser document/window DOM environment, for example "server-side Angular" is a thing, where some of the Angular code runs on the server to pre-render HTML to send to the client to minimize application startup delay or to allow web-browsers without JavaScript to access your webpages, in these situations the normal W3C DOM is no-longer available, but a "fake" DOM is available but it's provided by Angular - and it only works through Angular's abstractions - it won't work if you manipulate document directly, for example:



    function this_is_your_code_that_runs_in_nodejs() 

    tell_angular_to_make_my_sidebar_500px_wide(); // this works and Angular's built-in abstraction of the DOM makes the appropriate change to the rendered server-side HTML

    document.getElementById('mysidebar').style.width = 500px; // fails because `document` is not available







share|improve this answer



























    up vote
    2
    down vote













    Really good answer from @Dai above, I would like to add on top of that. For most cases, you should not manipulate the dom directly. There are cases where you have to and it's the right thing to do.



    For example, React and Vue has a concept of ref. Which can be though like an id and gives you the access to the dom node. Let's say you are building a chat application where you fetch old chats when the user scroll to the top and you need to keep the last visible chat in focus.



    This kind of situations are there and we need to access the dom. The good practice is to keep such code encapsulated and use the framework way of accessing something instead of reaching out for the document/dom.






    share|improve this answer




















      Your Answer





      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53028064%2fwhy-do-modern-javascript-frameworks-discourage-direct-interaction-with-the-dom%23new-answer', 'question_page');

      );

      Post as a guest






























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      4
      down vote













      @HDJEMAI linked to this article which I'll repeat, as it's good advice: https://www.reddit.com/r/javascript/comments/6btma7/whats_so_wrong_with_direct_dom_manipulation/



      I'll expand on some of those reasons below:



      • Modern frameworks like Angular and React are designed to hide the DOM because they want to abstract the DOM away. By using the DOM directly you break the abstraction and make your code brittle to changes introduced in the framework.


      • There are many reasons to want to abstract-away the DOM, and the Reddit page linked-to mostly focuses on "state management" because your framework (Angular, React, etc) will likely make assumptions about the DOM's state that will be broken if you manipulate the DOM directly, for example:



        function this_is_your_code() 

        tell_angular_to_make_my_sidebar_500px_wide();

        document.getElementById('mysidebar').style.width = 700px;

        var sidebar_width = ask_angular_for_sidebar_width();
        console.log( sidebar_width ); // will print "500px"




      • Another reason to abstract away the DOM is to ensure your code works with non-traditional DOMs besides the typical web-browser document/window DOM environment, for example "server-side Angular" is a thing, where some of the Angular code runs on the server to pre-render HTML to send to the client to minimize application startup delay or to allow web-browsers without JavaScript to access your webpages, in these situations the normal W3C DOM is no-longer available, but a "fake" DOM is available but it's provided by Angular - and it only works through Angular's abstractions - it won't work if you manipulate document directly, for example:



        function this_is_your_code_that_runs_in_nodejs() 

        tell_angular_to_make_my_sidebar_500px_wide(); // this works and Angular's built-in abstraction of the DOM makes the appropriate change to the rendered server-side HTML

        document.getElementById('mysidebar').style.width = 500px; // fails because `document` is not available







      share|improve this answer
























        up vote
        4
        down vote













        @HDJEMAI linked to this article which I'll repeat, as it's good advice: https://www.reddit.com/r/javascript/comments/6btma7/whats_so_wrong_with_direct_dom_manipulation/



        I'll expand on some of those reasons below:



        • Modern frameworks like Angular and React are designed to hide the DOM because they want to abstract the DOM away. By using the DOM directly you break the abstraction and make your code brittle to changes introduced in the framework.


        • There are many reasons to want to abstract-away the DOM, and the Reddit page linked-to mostly focuses on "state management" because your framework (Angular, React, etc) will likely make assumptions about the DOM's state that will be broken if you manipulate the DOM directly, for example:



          function this_is_your_code() 

          tell_angular_to_make_my_sidebar_500px_wide();

          document.getElementById('mysidebar').style.width = 700px;

          var sidebar_width = ask_angular_for_sidebar_width();
          console.log( sidebar_width ); // will print "500px"




        • Another reason to abstract away the DOM is to ensure your code works with non-traditional DOMs besides the typical web-browser document/window DOM environment, for example "server-side Angular" is a thing, where some of the Angular code runs on the server to pre-render HTML to send to the client to minimize application startup delay or to allow web-browsers without JavaScript to access your webpages, in these situations the normal W3C DOM is no-longer available, but a "fake" DOM is available but it's provided by Angular - and it only works through Angular's abstractions - it won't work if you manipulate document directly, for example:



          function this_is_your_code_that_runs_in_nodejs() 

          tell_angular_to_make_my_sidebar_500px_wide(); // this works and Angular's built-in abstraction of the DOM makes the appropriate change to the rendered server-side HTML

          document.getElementById('mysidebar').style.width = 500px; // fails because `document` is not available







        share|improve this answer






















          up vote
          4
          down vote










          up vote
          4
          down vote









          @HDJEMAI linked to this article which I'll repeat, as it's good advice: https://www.reddit.com/r/javascript/comments/6btma7/whats_so_wrong_with_direct_dom_manipulation/



          I'll expand on some of those reasons below:



          • Modern frameworks like Angular and React are designed to hide the DOM because they want to abstract the DOM away. By using the DOM directly you break the abstraction and make your code brittle to changes introduced in the framework.


          • There are many reasons to want to abstract-away the DOM, and the Reddit page linked-to mostly focuses on "state management" because your framework (Angular, React, etc) will likely make assumptions about the DOM's state that will be broken if you manipulate the DOM directly, for example:



            function this_is_your_code() 

            tell_angular_to_make_my_sidebar_500px_wide();

            document.getElementById('mysidebar').style.width = 700px;

            var sidebar_width = ask_angular_for_sidebar_width();
            console.log( sidebar_width ); // will print "500px"




          • Another reason to abstract away the DOM is to ensure your code works with non-traditional DOMs besides the typical web-browser document/window DOM environment, for example "server-side Angular" is a thing, where some of the Angular code runs on the server to pre-render HTML to send to the client to minimize application startup delay or to allow web-browsers without JavaScript to access your webpages, in these situations the normal W3C DOM is no-longer available, but a "fake" DOM is available but it's provided by Angular - and it only works through Angular's abstractions - it won't work if you manipulate document directly, for example:



            function this_is_your_code_that_runs_in_nodejs() 

            tell_angular_to_make_my_sidebar_500px_wide(); // this works and Angular's built-in abstraction of the DOM makes the appropriate change to the rendered server-side HTML

            document.getElementById('mysidebar').style.width = 500px; // fails because `document` is not available







          share|improve this answer












          @HDJEMAI linked to this article which I'll repeat, as it's good advice: https://www.reddit.com/r/javascript/comments/6btma7/whats_so_wrong_with_direct_dom_manipulation/



          I'll expand on some of those reasons below:



          • Modern frameworks like Angular and React are designed to hide the DOM because they want to abstract the DOM away. By using the DOM directly you break the abstraction and make your code brittle to changes introduced in the framework.


          • There are many reasons to want to abstract-away the DOM, and the Reddit page linked-to mostly focuses on "state management" because your framework (Angular, React, etc) will likely make assumptions about the DOM's state that will be broken if you manipulate the DOM directly, for example:



            function this_is_your_code() 

            tell_angular_to_make_my_sidebar_500px_wide();

            document.getElementById('mysidebar').style.width = 700px;

            var sidebar_width = ask_angular_for_sidebar_width();
            console.log( sidebar_width ); // will print "500px"




          • Another reason to abstract away the DOM is to ensure your code works with non-traditional DOMs besides the typical web-browser document/window DOM environment, for example "server-side Angular" is a thing, where some of the Angular code runs on the server to pre-render HTML to send to the client to minimize application startup delay or to allow web-browsers without JavaScript to access your webpages, in these situations the normal W3C DOM is no-longer available, but a "fake" DOM is available but it's provided by Angular - and it only works through Angular's abstractions - it won't work if you manipulate document directly, for example:



            function this_is_your_code_that_runs_in_nodejs() 

            tell_angular_to_make_my_sidebar_500px_wide(); // this works and Angular's built-in abstraction of the DOM makes the appropriate change to the rendered server-side HTML

            document.getElementById('mysidebar').style.width = 500px; // fails because `document` is not available








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 4 hours ago









          Dai

          70.6k13109197




          70.6k13109197






















              up vote
              2
              down vote













              Really good answer from @Dai above, I would like to add on top of that. For most cases, you should not manipulate the dom directly. There are cases where you have to and it's the right thing to do.



              For example, React and Vue has a concept of ref. Which can be though like an id and gives you the access to the dom node. Let's say you are building a chat application where you fetch old chats when the user scroll to the top and you need to keep the last visible chat in focus.



              This kind of situations are there and we need to access the dom. The good practice is to keep such code encapsulated and use the framework way of accessing something instead of reaching out for the document/dom.






              share|improve this answer
























                up vote
                2
                down vote













                Really good answer from @Dai above, I would like to add on top of that. For most cases, you should not manipulate the dom directly. There are cases where you have to and it's the right thing to do.



                For example, React and Vue has a concept of ref. Which can be though like an id and gives you the access to the dom node. Let's say you are building a chat application where you fetch old chats when the user scroll to the top and you need to keep the last visible chat in focus.



                This kind of situations are there and we need to access the dom. The good practice is to keep such code encapsulated and use the framework way of accessing something instead of reaching out for the document/dom.






                share|improve this answer






















                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  Really good answer from @Dai above, I would like to add on top of that. For most cases, you should not manipulate the dom directly. There are cases where you have to and it's the right thing to do.



                  For example, React and Vue has a concept of ref. Which can be though like an id and gives you the access to the dom node. Let's say you are building a chat application where you fetch old chats when the user scroll to the top and you need to keep the last visible chat in focus.



                  This kind of situations are there and we need to access the dom. The good practice is to keep such code encapsulated and use the framework way of accessing something instead of reaching out for the document/dom.






                  share|improve this answer












                  Really good answer from @Dai above, I would like to add on top of that. For most cases, you should not manipulate the dom directly. There are cases where you have to and it's the right thing to do.



                  For example, React and Vue has a concept of ref. Which can be though like an id and gives you the access to the dom node. Let's say you are building a chat application where you fetch old chats when the user scroll to the top and you need to keep the last visible chat in focus.



                  This kind of situations are there and we need to access the dom. The good practice is to keep such code encapsulated and use the framework way of accessing something instead of reaching out for the document/dom.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 4 hours ago









                  aks

                  2,04621643




                  2,04621643



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53028064%2fwhy-do-modern-javascript-frameworks-discourage-direct-interaction-with-the-dom%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      What does second last employer means? [closed]

                      List of Gilmore Girls characters

                      Confectionery