-1

I have a piece of JavaScript code that I want to translate it to jQuery:

 var target = document.getElementById('myID');

 ... do additional work here ...

The code above works just fine, no problem. However if I try to use it this way, nothing happens:

 var target =  $("#myID");

What is the equivalent of document.getElementById in jQuery?

P.S. jQuery library is loaded and the code is withing

    $(document).ready(function () {


       var target = document.getElementById('myID');

       ... do additional work here ...


       var target =  $("#myID");

    });
10
  • 1
    any error in console?
    – Mritunjay
    Jul 23, 2014 at 6:52
  • 3
    Included Jquery library..? getting any errors like $ is not defined displaying in the console.? Jul 23, 2014 at 6:52
  • 1
    "do additional work here" what is the additional work there? Jul 23, 2014 at 6:53
  • 1
    This is the most basic thing you can do in jQuery. Have you tried debugging in any way? Included jquery.js? Checked the console for errors? Does the element actually exist on DOM load? Included a DOM Ready handler? Jul 23, 2014 at 6:53
  • 2
    Thanks @undefined it works! Didn't knew about the get(0) ... :) great!
    – David Dury
    Jul 23, 2014 at 6:56

3 Answers 3

3

As @undefined pointed in a comment above, the correct answer is:

var target = $("#myID").get(0);
5
  • 1
    Why the downvotes? You can answer your own question, no?
    – Ram
    Jul 23, 2014 at 7:01
  • @undefined: actually you answered my question :) but whatever :) you can answer and I will mark it as correct!
    – David Dury
    Jul 23, 2014 at 7:02
  • 2
    @David Dury - +1 ,you asked good question but you didn't know how to post the question more understandable for others Jul 23, 2014 at 7:05
  • @Sudharsan: I just wanted to know the jQuery equivalent of document.getElementById. And as I pointed out the document.getElementById it was working correct. Maybe I should have mentioend that jQuery was loaded and in place.
    – David Dury
    Jul 23, 2014 at 7:07
  • 1
    @DavidDury - Then your title be in your comment - "jQuery equivalent of document.getElementById" Jul 23, 2014 at 7:08
1

how about var target = $("#myID")[0];

recently i debug the code :

var map = new google.maps.Map(document.getElementById("myId"), mapOptions);

it works well only with getElementById , and the $("#myID") not work.

1

try this code it will help you..

var target = $("#myID")[0];

thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.