Rahul
Rahul

Reputation: 135

Assign Div id to variable jQuery

I am trying to assign div id to a variable in jQuery .

 var tbdiv = null;
    tbdiv= $('#mydiv');

But this is throwing error in my jQuery file as ' Invalid argument '.

I am trying to do the following code which is in javascript

var tbdiv =document.getElementById('mydiv');

Upvotes: 2

Views: 34562

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

I can't see any reason that the code

var tbdiv = null;
tbdiv= $('#mydiv');

...would throw any kind of exception provided that

  1. jQuery is loaded, and

  2. jQuery has the $ symbol. Some other libraries use it, and so jQuery offers noConflict mode. If you've included code somewhere calling noConflict, $ will no longer refer to jQuery and you'd have to use this instead:

    tbdiv = jQuery('#mydiv');
    

Note that your JavaScript example is wrong. It would be getElementById('mydiv') (without the #, since the argument to getElementById is an ID, not a selector).

Upvotes: 0

Greg B
Greg B

Reputation: 14888

If you are trying to select the div then the following should work:

var tbdiv = $('#mydiv');

If you wan't to select the ID of the div, then why use jQuery, you already know the ID because you are using it to make the call to jQuery.

Is jQuery loaded? Are you getting any other errors in the console?

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382666

You can use attr:

var tbdiv= $('#mydiv').attr('id');
// or: var tbdiv = $('#mydiv')[0].id; 

I would though simply do:

var tbdiv= '#mydiv'

to assign id.


If you MEANT assigning element itself, this should work fine:

var tbdiv = $('#mydiv');

Or with vanilla JS:

var tbdiv = document.getElementById('mydiv');

Upvotes: 8

Related Questions