3

I'm a newbie in JavaScript, I use a piece of code to convert JSON to HTML table.

And here is the JavaScript code:

function buildHtmlTable(myList,printSource,tablename) {
     var columns = addAllColumnHeaders(myList);
     var title = document.getElementsByTagName("caption");
     title.innerHTML="<h>"+printSource+"</h>";
     for (var i = 0 ; i < myList.length ; i++) {
         var row$ = $('<tr/>');
         for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
             var cellValue = myList[i][columns[colIndex]];

             if (cellValue == null) { cellValue = ""; }

             row$.append($('<td/>').html(cellValue));
         }
         $("#excelDataTable").append(row$);
     }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(myList) {
     var columnSet = [];
     var headerTr$ = $('<tr/>');

     for (var i = 0 ; i < myList.length ; i++) {
         var rowHash = myList[i];
         for (var key in rowHash) {
             if ($.inArray(key, columnSet) == -1){
                 columnSet.push(key);
                 headerTr$.append($('<th/>').html(key));
             }
         }
     }
     $("#excelDataTable").append(headerTr$);

     return columnSet;
}

Here is my HTML code:

<body onload="buildHtmlTable(data_epgd, epgd);">
    <table id="excelDataTable" border="1">
        <caption>sn</caption>
    </table>
</body>

As you can see, there is a usage of $("#excelDataTable"). I thought it's just like document.getElementById function to find an element in HTML.So I use document.getElementById to replace it. But when I did this, the code didn't work any more.So can somebody explain what is the difference between document.getElementById(excelDataTable) and $("#excelDataTable")? And why I can't use document.getElementById(excelDataTable) as alternative?

benomatis
  • 5,035
  • 7
  • 30
  • 51
Coding_Rabbit
  • 925
  • 3
  • 13
  • 34
  • 3
    `$('selector')` in jQuery returns a jQuery object while `getElementById('id')` returns an Element object (they are different objects that behave slightly differently) – blurfus Apr 23 '16 at 07:46
  • `$` is more like `document.querySelectorAll`. – Oriol Apr 23 '16 at 08:06

3 Answers3

3

Using the $() is actually more than just a selector, it also wraps it in a jQuery object. Later in your script your using jQuery functions like .append, and those don't work on vanilla objects. What you can do is select it regularly and when you need jQuery functions you wrap ($()) it again.

Furthermore a selector should be a string ('element') and not a variable (element), like Fred mentioned.

Haroen Viaene
  • 1,817
  • 16
  • 28
  • Does it matter to use `""` instead of `''`. I'm kinda confused about that, in most situation, do they both work fine? – Coding_Rabbit Apr 23 '16 at 07:56
  • `''` and `"""` are [equivalent](http://stackoverflow.com/a/944092/3185307). It's best practice to just use one style throughout your codebase though. Also worth noting that if you're in a `json` file, only `""` is allowed. – Haroen Viaene Apr 23 '16 at 07:58
  • 1
    Thank you for your useful and detailed answer! – Coding_Rabbit Apr 23 '16 at 08:08
  • I noticed that FredMaggiowski said $(document.getElementById()) is a bad expression, but if I want the string "#excelDataTable" in $("#excelDataTable") to be a variable, can I just use a variable replace the string, like $(variable)? – Coding_Rabbit Apr 23 '16 at 08:09
  • > a selector should be a string (`'element'`) and not a variable (`element`) Your statement is not true. `document.getElementById('element')` can be rewritten as `var element = 'element'; document.getElementById(element)`. One should use a JavaScript String. Either a literal like `'string'` or a variable/function whose value/return value evaluates to JavaScript String – vdua Apr 23 '16 at 08:09
  • So if my variable represents a string, it's ok to use $(variable)? – Coding_Rabbit Apr 23 '16 at 08:24
  • Yes, that's possible. – Haroen Viaene Apr 23 '16 at 08:25
  • OK, and why the string inside the bracket is "#excelDataTable" instead of "excelDataTable"? – Coding_Rabbit Apr 23 '16 at 08:26
  • Because the `#` stands for looking for an id, you can use any css query in `$()` – Haroen Viaene Apr 23 '16 at 08:27
  • So using the version without `#` is incorrect, or they are both ok? – Coding_Rabbit Apr 23 '16 at 09:30
  • Using `$()` in jQuery is "equivalent" to using `document.querySelectorAll()`, with the notable difference that only the first one will allow you to use jQuery functions like `.append()`. Using it without the `#` would mean you'd look for a tag (like `

    `) with the name `excelDataTable`

    – Haroen Viaene Apr 23 '16 at 09:33
0

The line below will return a jQuery object

$("#excelDataTable") 

Meanwhile using

document.getElementById(excelDataTable)

will return you a DOMElement object, which obviously doesn't have jQuery methods.

jQuery accepts also a DOM element to be passed to the constructor. Thus eventually you could do so

$(document.getElementById(excelDataTable))
Igor Bukin
  • 876
  • 6
  • 13
  • It should be `$(document.getElementById(excelDataTable))` or `$(document.getElementById("excelDataTable"))`? – Coding_Rabbit Apr 23 '16 at 07:52
  • The second one, `$(document.getElementById("excelDataTable"))` – Haroen Viaene Apr 23 '16 at 07:54
  • 1
    Doing $(document.getElementById()) is the worst thing I've ever read. You're using jquery? Use it. You don't want to use jquery, use plain js. Don't use both – fredmaggiowski Apr 23 '16 at 07:54
  • Thank you for your helpful and detailed answer! – Coding_Rabbit Apr 23 '16 at 08:07
  • @FredMaggiowski, we hear what we want to hear... I didn't say it makes sense to combine it into a single expression. It was just an example for the statement above that jQuery accepts DOM Elements as well. Thus in case somewhy there is a DOM element object, you always can convert it to jQuery object – Igor Bukin Apr 23 '16 at 09:46
0

$() is a shorthand for jQuery(). it is actually a function which returns a collection of jquery compatible objects so that jquery functions can be used on these elements like append(),empty() etc.$() is commonly used as a selector function in Jquery but it is more than a selector...

  1. we can pass it a selector to get a collection of matching elements wrapped into collection of jquery objects from the DOM ..like $('.btnClass'),$('#id'),$('table').

  2. we can pass it a string of HTML to turn into a DOM element which you can then use it into the document.

    3.we can pass it a DOM element or elements that you want to wrap with the jQuery object.

    For more details refer documentation documentation