Farrukh Zaman
Farrukh Zaman

Reputation: 49

Pass variable to getElementById

I have multiple tables which are generated by loop and each table have different ids. Like (table1,table2,table3 and so on.) I want to pass these id to getElementById function using jquery each function. Here is my code

 $(document).ready(function () {
    $('.table', this).each(function (index, element) {
        tnames = $(element).attr('id');

        //alert(tnames)
        var elem5 = document.getElementById(tnames);
        alert(elem5);

    });
});

tnames alert fine. but when i pass tname to getElementById function it return null or object. I want it should return ids as returning alert(tname);

Any help and suggestions. Please?

Upvotes: 1

Views: 2179

Answers (3)

mplungjan
mplungjan

Reputation: 177950

If you for sure have

<table class="table" id="table1"></table>
<table class="table" id="table2"></table>
<table class="table" id="table3"></table>

Then you can do

$(function () {
  $('.table').each(function () {
    console.log(this.id); // or the more verbose $(this).attr("id");
  });
});

Full example below:

$(function() {
  $('.table').each(function() {
 
    var tableID = this.id; // here is the ID

    console.log(tableID); 


    // if you need the table itself
    var elem5 = $(this).get(0); // get the DOM table from jQuery
    console.log("using jQuery get",elem5);

    elem5 = document.getElementById(tableID); // get the DOM table using DOM access
    console.log("using getElementById",elem5);
  
   
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table" id="table1"><tr><td>Table1</td></tr></table>
<table class="table" id="table2"><tr><td>Table2</td></tr></table>
<table class="table" id="table3"><tr><td>Table3</td></tr></table>

Upvotes: 1

Khanjan Bhatt
Khanjan Bhatt

Reputation: 94

I hope following code will help you to find an element's id. Following code will alert table id.

$("document").ready(function () {           
        var tableid= $('table').attr('id');

        var element = document.getElementById(tableid);
        alert(element.id);

});

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Stick with jquery

 var elem5 = $("#"+tnames);
 alert(elem5.html());

Upvotes: 0

Related Questions