I use a script that returns a DOM in the body of the callback when this is called: enter image description here

Why can I get the value of the id attribute of a div block with getAttribute() and can't get with the help of attr() ? These two functions do not the same thing?

  • Do you have any libraries connected? I just don’t remember attr in standard js - Michael
  • one
    getAttribute is javascript , attr is jquery , respectively, the second works with jquery objects, and the first with regular DOM objects is Rostyslav Kuzmovych

1 answer 1

The differences between attr() and getAttribute() are mainly in the fact that attr() is a jquery library function that works with a jquer object (which is some kind of wrapper over a standard house object). getAttribute() in turn, is the standard js method, and it works with house objects, but naturally it does not work with a jquer object, since this object does not have such a method, for the same reason attr() will not work with a regular object.

Here is a small illustration:

 var jqueryA = $('#a'); var jsA = document.querySelector('#a'); console.log(jqueryA.attr('data-test')); try { console.log(jqueryA.getAttribute('data-test')); } catch (e) { console.log(e.message); } // console.log(jsA.getAttribute('data-test')); try { console.log(jsA.attr('data-test')); } catch (e) { console.log(e.message); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-test="123" id="a"></div>