programing

document.getElementById 대 jQuery $ ()

nasanasas 2020. 10. 3. 10:56
반응형

document.getElementById 대 jQuery $ ()


이것은 :

var contents = document.getElementById('contents');

이것과 동일 :

var contents = $('#contents');

jQuery가로드되면?


정확히!!

document.getElementById('contents'); //returns a HTML DOM Object

var contents = $('#contents');  //returns a jQuery Object

jQuery에서와 동일한 결과를 얻으려면 document.getElementByIdjQuery 객체에 액세스하고 객체의 첫 번째 요소를 가져올 수 있습니다 (자바 스크립트 객체는 연관 배열과 유사하게 작동 함).

var contents = $('#contents')[0]; //returns a HTML DOM Object

아니.

호출 document.getElementById('id')하면 원시 DOM 개체가 반환됩니다.

호출 $('#id')은 DOM 개체를 래핑하고 jQuery 메서드를 제공하는 jQuery 개체를 반환합니다.

따라서, 당신은 단지 같은 jQuery를 메서드 호출 할 수 있습니다 css()또는 animate()$()전화를.

당신은 또한 쓸 수 $(document.getElementById('id'))JQuery와 개체를 반환하고에 해당되는, $('#id').

을 작성하여 jQuery 객체에서 기본 DOM 객체를 가져올 수 있습니다 $('#id')[0].


비슷하지만 동일하지는 않습니다. 그들은 동일한 요소를 얻지 만 jQuery 버전은 jQuery 객체에 래핑됩니다.

동등한 것은 다음과 같습니다.

var contents = $('#contents').get(0);

아니면 이거

var contents = $('#contents')[0];

이것들은 jQuery 객체에서 요소를 가져옵니다.


속도 차이에 대한 참고 사항. 다음 스 니펫을 onclick 호출에 연결하십시오.

function myfunc()
{
    var timer = new Date();

        for(var i = 0; i < 10000; i++)
        {
            //document.getElementById('myID');
            $('#myID')[0];
        }


    console.log('timer: ' + (new Date() - timer));
}

교대로 하나를 주석 처리 한 다음 다른 하나를 주석 처리합니다. 내 테스트에서

document.getElementById를 대해 평균 35ms (에서 변동 25ms까지 52ms약에 15 runs)

반면에

jQuery를 대해 평균 200 밀리 초 (이르기 181ms까지 222ms약에 15 runs).

이 간단한 테스트에서 jQuery가 약 6 배 더 오래 걸렸음을 알 수 있습니다 .

Of course, that is over 10000 iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate and .fadeTo. But yes, technically getElementById is quite a bit faster.


No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contents was matched.

The DOM element returned by document.getElementById('contents') allows you to do things such as change the .innerHTML (or .value) etc, however you'll need to use jQuery methods on the jQuery Object.

var contents = $('#contents').get(0);

Is more equivilent, however if no element with the id of contents is matched, document.getElementById('contents') will return null, but $('#contents').get(0) will return undefined.

One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned. However you will get errors if you try to perform operations on the null returned by document.getElementById


No, actually the same result would be:

$('#contents')[0] 

jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.

Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection

When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object


In case someone else hits this... Here's another difference:

If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.

This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:

var contents = document.getElementById('a/b/c');

was able to find my element but:

var contents = $('#a/b/c');

did not.

Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:

var contents = $('.myclass[name='a/b/c']);

Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.


var contents = document.getElementById('contents');

var contents = $('#contents');

The code snippets are not the same. first one returns a Element object (source). The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById() for efficiency.

In both the cases if more than one element found only the first element will be returned.


When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)

// HANDLE: $(#id)
} else {
    elem = document.getElementById( match[2] );

One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.

Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.

<body id="content">
   <h1>Header!</h1>
   <form>
      <div id="content"> My Form </div>
   </form>
</body>

It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.


jQuery is built over JavaScript. This means that it's just javascript anyway.

document.getElementById()

The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.

Jquery $()

Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.


I developed a noSQL database for storing DOM trees in Web Browsers where references to all DOM elements on page are stored in a short index. Thus function "getElementById()" is not needed to get/modify an element. When elements in DOM tree are instantiated on page the database assigns surrogate primary keys to each element. It is a free tool http://js2dx.com


All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :

I have an HTML :

<div id="contents"></div>

Go to console (cntrl+shift+c) and use these commands to see your result clearly

document.getElementById('contents')
>>> div#contents

$('#contents')
>>> [div#contents,
 context: document,
 selector: "#contents",
 jquery: "1.10.1",
 constructor: function,
 init: function …]

As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:

$('#contents')[0]
>>> div#contents

참고URL : https://stackoverflow.com/questions/4069982/document-getelementbyid-vs-jquery

반응형