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?
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.
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))
$() 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...
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').
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
Related
There is the following code with jQuery:
var ths = $(".timetable__table th");
var th;
for (var i = 0; i < ths.size(); i++) {
th = ths.get(i).text();
console.log(th);
}
When I try to execute this code I get the following exception: TypeError: ths.get(...).text is not a function. I don't understand why it occurs, I just need to get the text value of a tag. How can I fix it?
Do like this, Use .each() function at this context to traverse over a collection of jquery object.
$(".timetable__table th").each(function(){
console.log($(this).text());
});
.get(index) would return a javascript object and that does not contains a function called .text()
Note: Keep in mind that .size() has been deprecated from the version 1.8 use .length instead
because .get() returns the dom element not a jQuery object(the .text() is a method of jQuery wrapper object) use .eq() which will return a jQuery object
var ths = $(".timetable__table th");
var th;
for (var i = 0; i < ths.size(); i++) {
th = ths.eq(i).text();
console.log(th);
}
You need to iterate array like th[i] :
var ths = $(".timetable__table th");
var th;
for (var i = 0; i < ths.size(); i++) {
th = ths[i].text();
console.log(th);
}
But easiest way is below where you can skip for loop and simply use .each :
$(".timetable__table th").each(function(){
console.log($(this).text());
});
.get() returns the underlying DOM element(s), which don't have a text() method. Use .eq() instead.
Looks like you didn't decide if you want to use the DOM or jQuery. Your code can be simplified to something like:
$(".timetable__table th").each(function(index, el) {
console.log($(el).text());
});
this is my code :
html = "";
for (i = 0; i < id_array.length; i++){
html = html.concat($(id_array[i]).clone(true));
}
console.log(html);
The id_array contains 3 ids of the <tr> tag . Instead of the html code from the ids , the result of the html variable is object object object ... Why ? How do I get the html code from this id ?
This is my html code , it is not written by me , it is generated by JQgrid plugin. so i took a picture:
It looks like your want to call outerHTML. In order to do it, you need the native DOM element, you can get it using [0] or get(0) :
var html = "";
for (i = 0; i < id_array.length; i++){
html += $(id_array[i])[0].outerHTML;
}
console.log(html);
clone returns jQuery objects. You don't want to concat them with an empty string. Instead, use an array to store them:
trs = [];
for (i = 0; i < id_array.length; i++){
trs.push($(id_array[i]).clone(true));
}
console.log(trs);
You don't want to use HTML strings when dealing with the DOM.
It seems you may want the outer HTML of the TR elements. Some browsers support it, but not all (and surprisingly not jQuery). In this case you can do something like:
var id_array = ['tr0','tr1','tr2'];
var html = "";
var tbody = $('<tbody>');
for (i = 0; i < id_array.length; i++) {
tbody.append($('#' + id_array[i]).clone(true));
html += tbody.html();
tbody.html('');
}
I have this code which manipulates the asp.net treeview html code.
This code gets run frequently, so its important that it runs as fast as possible.
I want to learn more about jquery selectors and improving its speed. So far I was able to get this code myself.
Some things I am not sure about is if you want the third child element, do I use [2] or .eq(2) or :nth-child(2)? Also what if I use $ to select something that was from an array of selected stuff, is this necessary, or is it already selected?
Does anyone know any tricks or hints I can do to improve my jquery select efficiency?
Thanks.
function showResultsOnTreeview(treeviewID, filenameDictionary) {
var sectionNodes = $("#" + treeviewID + " > table");
var numOfSections = sectionNodes.length;
var i, j, sectionName, divContainer, itemNodes, numOfItems, itemName, itemTag, itemPath;
for (i = 0; i < numOfSections; i += 1) {
sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');
divContainer.hide();
itemNodes = $('table', divContainer);
numOfItems = itemNodes.length;
for (j = 0; j < numOfItems; j += 1) {
itemTag = $('td', $(itemNodes[j])).eq(2);
itemTag.removeClass('treeViewResult');
itemName = getNameFromItem($(itemNodes[j]).text());
itemPath = filenameDictionary[itemName];
if (itemPath != null) {
if (itemPath.indexOf(sectionName + "/" + itemName) != -1) {
itemTag.addClass('treeViewResult');
divContainer.show();
}
}
}
}
}
There is some optimisation you can do. The first on is for sure to use .eq() instead of []. Like here, you hare creating a jQuery object :
var sectionNodes = $("#" + treeviewID + " > table");
But then later, you do this :
sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');
Here you are creating 2 more, unneeded, jquery object, you could just do this :
sectionName = sectionNodes.eq(i).text();
divContainer = sectionName.next('div');
Then, i do't know if you have a different way to do it, but if you can remove the "loop in a loop", that would be great.
After, instead of using context selectore ($('selector', $element)), use find. Context use find so it will reduce the number of function calls. Take this line for example :
$('td', $(itemNodes[j])).eq(2)
You are creating 2 jQuery object when you can do the same without an extra object and could use .find():
itemTag = itemNodes.eq(j).find('td').eq(2);
Basicly, use .find() instead of context and avoid creating unneeded jQuery object. Hope that will help.
there is long string, like
<td>sdfaf</td><td width='1'></td><td width='1'>sdfdsf</td><td></td>
Is there a simple regex method to delete contents inside tags, convert it to
<td></td><td width='1'></td><td width='1'></td><td></td>
I know jquery html() and empty() can do the work, but I want to find a pure javascript method to do it.
thanks
Assuming your "string" comes from a table in your document, here's how to do it in vanilla javascript :
var cells = yourtable.getElementsByTagName('td');
for (var i=0; i<cells.length; i++) cells[i].innerHTML = '';
(if you just have the string, you may simply create a tr node and set this string as innerHTML)
try this simple code
var tds = document.getElementsByTagName("td");
for ( var counter = 0; counter < tds.length; counter++ )
{
tds[ counter ].innerHTML = "";
}
Rough and ready, assuming no angle brackets between or inside the tags:
str = str.replace( />[^<]+<\//g, '></' );
Please let me know how to assign id for table header (th) with class="tableHeader" and table id="requestview_table" using javascript(after html table is constructed). Currently, the table headers don't have any id.
Please let me know how to insert id (any number) for with class tableHeader.
$("#requestview_table").find("th.tableHeader").each(function(index) { $(this).attr('id','header' + index); });
m0sa's answer is cleaner (yeay! jQuery) but if you want a JavaScript only solution then this is my stab at it:
Firstly you need a method to get items based on class name (which is something I modified from here: http://www.tek-tips.com/viewthread.cfm?qid=1143850&page=1).
function getElementsByClassName(strClassName, obj) {
var arrClassElements = [];
if (obj) {
if (obj['className'] && obj.className.indexOf(strClassName) != -1) {
arrClassElements.push(obj);
}
for (var i = 0; i < obj.childNodes.length; i++) {
arrClassElements = arrClassElements.concat(getElementsByClassName(strClassName, obj.childNodes[i]));
}
}
return arrClassElements;
}
Then you use this to iterate through the elements it picked up, using setAttribute to add an ID to the element.
var headers = getElementsByClassName('tableHeader', document.getElementById('requestview_table'));
for(var i=0;i<headers.length;i++){
headers[i].setAttribute('id', 'header' + i)
alert(headers[i].id);
}
This is it working here: http://jsfiddle.net/jonathon/W6JyE/
Again, I recommend you use jQuery if you can. It's much better and cleaner for doing the type of operations you're looking to do. This is just one of many alternative solutions.