开发者

Convert jQuery element to a regular dom element

开发者 https://www.devze.com 2022-12-23 08:04 出处:网络
A regular dom element is such as: document.getElementById(\'a\') or document.createElement(\'div\') But jQuery returns elements in another format, so for instance I\'d like to convert what is retu

A regular dom element is such as:

document.getElementById('a')

or

document.createElement('div')

But jQuery returns elements in another format, so for instance I'd like to convert what is returned by $('#a') to the same result as what is returned by document.getElementById('a')

开发者_JS百科

Is this possible using jQuery?

thanks


You can reference the DOM element with .get(0) or [0], eg $('#foo')[0] assuming there is just one.


$('#a')[0]

// oops my answer is too short


That is what get() method was made for by JQuery team, consider:

var elem = $('#a')[0];

Or

var elem1 = $('#a').get(0);
var elem2 = document.getElementById('a');
alert(elem1 === elem2);

or longer version:

<!DOCTYPE HTML>
<html>
<body>   
<a id='a'></a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
  <script>

    var elem1 = $('#a').get(0);
    var elem2 = document.getElementById('a');
    alert(elem1 === elem2);

  </script>  
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消