Jquery get text value of some selector using index in array - javascript

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());
});

Related

Why can't use document.getElementById to replace $ in JavaScript?

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

How to get width of each dom element in array?

footLinks is an array of selected DOM elements via jquery. Here's the code im working on:
var footLinks = $('.links li');
for (var i = 0; i < footLinks.length; i++) {
var footLink = footLinks[i];
var footLinkWidth = footLink.width();
console.log('Width: ' + footLinkWidth);
}
How do I get each element's width?
I think it would be better if you wrote it like this:
$('.links li').each(function(d) {
console.log("Width: "+$(this).width())
});
jQuery returns object in array, and when you want to use each DOM element in loop that is work with JavaScript function, but width() is not native function, if you want to get width using jQuery width() method then create jquery object like $(footLink) so you can also use offsetWidth native method
$(footLink).width();
OR
footLink.offsetWidth;
Use jQuery wrapper for the footLink:
var footLinks = $('.links li');
for (var i = 0; i < footLinks.length; i++) {
var footLink = footLinks[i];
var footLinkWidth = $(footLink).width();
console.log('Width: ' + footLinkWidth);
}

getElementById to select class instead of id

I've got a bit of jQuery that outputs some HTML to an id, however in my code it must output to a class. Any ideas how I can achieve this?
document.getElementById("content").innerHTML=output;
<div class="content> </div>
I've tried getElementsByClass but it doesn't seem to work for me.
What you have there isn't jquery, it's raw JS and if you already have jQuery in your project, it's a bit easier with jQuery:
$(".content").html(output);
Use the getElementsByClassName method.
[0] is missed in the javascript. Thats the reason , you are not able fetch the records.
document.getElementsByClassName("content")[0].innerHTML = output;
getElementsByClassName returns an array of all matching elements. Try looping through this array and adjusting each array item
var elements = document.getElementsByClassName('class-name');
for ( var i = 0; i < elements.length; i++ )
{
elements[i].innerHTML = output;
}
getElementsByClassName returns an array, so assuming this is the first content in your document, use:
document.getElementsByClassName("content")[0].innerHTML = output;
If there are more than one element, you'd use a loop to loop through them and target the element you wish, e.g
var content = document.getElementsByClassName('content');
for (var i = 0; i < content.length; i++) {
content[1].innerHTML = "Second element with class content";
content[3].innerHTML = "Fourth element with class content";
}
jsFiddle here
You can use querySelectorAll for this purpose
document.querySelectorAll(".content")[0].innerHTML = output;
documet.querySelectorAll returns the elements with matching selectors.

is there a simple way to use javascript replace to remove contents inside tags

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, '></' );

Using .attr() with .get() Issues

I am trying to store an array of objects in an array by going through each paragraph element in a div container with the .get() method. I try to access the attribute with .attr() but it doesn't seem to work. How would I modify this code in order to be able to access the 'id' attribute of each message?
var messages = $("#message_container p").get();
var idstest = [];
for (int i = 0; i < messages.length; i++){
idstest.push(messages[i].attr("id"));
}
I think it has to do with some fundamental incompatibility with .get() and .attr(). When I 'alert' the objects provided by .get() I get [object HTML---]. I'm assuming that is not the form necessary in order to use .attr?
get will give you the DOM element. These are NOT jquery objects so you can't use attr on them. There's no reason to use get at all here.
var messages = $("#message_container p");
var idstest = [];
messages.each(function(){
idstest.push($(this).attr("id"));
});
http://jsfiddle.net/ujdeH/
EDIT: You also can't use int.
If for some reason you did want to use get to get the raw DOM elements, you would then just use .id:
http://jsfiddle.net/ujdeH/1/
var messages = $("#message_container p").get();
var idstest = [];
for (var i = 0; i < messages.length; i++) {
idstest.push(messages[i].id);
}
try instead:
var idstest = [];
$("#message_container p").each(function(i){
idstest.push($(this).attr("id"));
});
Just wanted to add the $.map shortcut: http://jsfiddle.net/UuWq3/.
var idstest = $.map(messages, function(elem) {
return $(elem).attr("id");
});
$.map returns a new array based on the original array (or jQuery object). The array returned is constructed with the function you pass (in this case, messages is transformed by the function such that each element is replaced with it's ID).
You should wrap the object in jQuery container:
$(messages[i]).attr("id")
Actually no need for jQuery here, this pure JavaScript will work just fine on all browsers:
var idstest = [];
var container = document.getElementById("message_container");
if (container) {
var messages = container.getElementsByTagName("p");
for (var i = 0; i < messages.length; i++) {
idstest.push(messages[i].id);
}
}
jQuery is all good and powerful, but if you can achieve the same task with short/easy enough pure JS then why not?
This said, if all your existing code is jQuery then you might be better off sticking with it (using the code from other correct answers here) just for sake of consistency and readability.

Categories