Get as an object using id in jquery

I have a method that takes obj as a parameter. I cannot change the signature, and I want to reuse it. I have to send the element as an object to this parameter, so I'm not sure how to do this. Can anyone show me?

function someUsefulFunction(obj) { var id = obj.id; //do other stuff } { ... var myElement = $('#myElement'); someUsefulFunction(myElement); //getting error "TypeError: obj.id is undefined" ... } 
+5
source share
2 answers
 var myElement = document.getElementById('myElement'); 

looks like a waiting dom node, so you can do it in the old fashioned simple js way.

or if you want to do it using jquery,

 var myElement = $('#myElement').get(0); 
+4
source

You need to change:

 var id = obj[0].id; 

 function someUsefulFunction(obj) { var id = obj.id; console.log(id); } var myElement = $('#myElement').get(0); someUsefulFunction(myElement); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myElement"></div> 

Alternative you can:

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

 function someUsefulFunction(obj) { var id = obj[0].id; console.log(id); } var myElement = $('#myElement'); someUsefulFunction(myElement); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myElement"></div> 
+4
source

Source: https://habr.com/ru/post/1206670/


All Articles