Being fairly new to jquery and javascript I can't seem to understand how the .text() method really works. I read through the jQuery documentation but still can't figure it out.
for (var i=0; i < arrayLength; i++){
var currentElement = $(".artist")[i];
var currentArtist = currentElement.text;
console.log(currentElement);
console.log(currentArtist);
}
currentArtist returns "undefined" in the console. It works fine on the $(".artist") alone, but not when I use the [i] or anything additional for that matter. What am I missing here? How else could I grab a text value inside a selector?
By using the [] operator on jQuery object you're accessing the raw element node that was found by jQuery. This raw element doesn't have the jQuery methods anymore, nor a text property.
If you want to get single element from jQuery object and keep the jQuery wrapper, use eq method.
var artistElement = $(".artist").eq(i);
artistElement.text(); // gets the text content of the element
The code you've posted is also not very optimized. For instance, with every loop iteration you're searching the document over and over again for elements with class artist. Better to cache that search result in a variable before performing the loop. And if the loop iterates over all .artist elements, you can use jQuery's each method.
$(".artist").each(function () {
var artist = $(this); // this poits to the raw element thus wrapping into jQuery object
console.log(artist.text());
});
var currentArtist = currentElement.text;
Should be:
var currentArtist = currentElement.text();
You should use a each():
$(".artist").each(function(i,val){
var currentArtist = $(val).text();
console.log(val);
console.log(currentArtist);
});
$(".artist") produce a jQuery object that could be like this:
[div, div, div, div, prevObject: jQuery.fn.jQuery.init, context: document, selector: ".artist"...]
So the result of $(".artist")[i] is a HTMLElement and do not have a text method, that's why you're getting undefined
Also text() is a function and may be followed with ()
But if you want to keep the for loop you can do
for (var i=0; i < arrayLength; i++){
var currentElement = $(".artist")[i];
var currentArtist = $(currentElement).text();
console.log(currentElement);
console.log(currentArtist);
}
.text() shows the text of an html element or set of html elements that would be visible to the user.
Related
I have little to no experience of JavaScript but I do know that the getElementID only carries one value so how can I have 2 values passed?
Can I use it twice like I have down below or would I be better to use another GetElementBy/GetElementsBy method to do it?
<script type="text/javascript">
$(document).ready(function () {
hash();
function hash() {
var hashParams = window.location.hash.substr(1).split('&');
for (var i = 0; i < hashParams.length; i++) {
var p = hashParams[i].split('=');
document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(p[1]);
document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(p[1]);;
}
}
});
</script>
EDIT
So I've decided to use the loop twice and its working but the values I'm passing contain text I need removed. Is there a way in which I can cut off the split after a certain character? Here is my new code
<script type="text/javascript">
$(document).ready(function () {
hash();
function hash() {
var hashParams = window.location.hash.substr(1).split('#');
for (var i = 0; i < hashParams.length; i++) {
var p = hashParams[i].split('=');
document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(p[1]);
}
var hashParams = window.location.hash.substr(1).split('&');
for (var i = 0; i < hashParams.length; i++) {
var p = hashParams[i].split('=');
document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(p[1]);;
}
}
});
</script>
And here is the text that appears in the search bar when forwarded from the previous page.
localhost:56363/Bookings.aspx#start=27/02/2018 12:30&end=27/02/2018 17:30
The start and end input boxes fill with the values but the start input box (27/02/2018 12:30&end) has characters I want cut off (&end).
Is there a way to stop a split after a certain character?
Using it twice as you have is perfectly acceptable. And, if they are separate things, then it makes sense.
While you could also use getElementsByTagName(), getElementsByName() or getElementsByClassName(), usually using document.querySelectorAll() is the more modern choice.
If they have something in common with them (like say a class), you could use it like this:
const nodeList = document.querySelectorAll('.classToGet');
Array.prototype.forEach.call(nodeList, element => element.value = decodeURIComponent(p[1]));
document.querySelectorAll() (as well as the getElementsBy functions) return a NodeList, which is kind of like an Array, but doesn't have an Array's functions, so you need to Array.prototype.forEach.call() to loop over them.
document.querySelectorAll() accepts a string like you would give to CSS, and the NodeList has all elements that match that.
And FYI, there is an equivalent document.querySelector() which gets a single element, so you could use it for IDs:
document.querySelector("#<%=start.ClientID%>")
Note the # like you would have for CSS at the beginning.
ID is a unique identifier, unlike class, so there should be only one of it with the same name in your DOM.
getElementById is intended to find the one element in the DOM with the specified ID.
If you need to get multiple elements, then yes make multiple calls to getElementById.
See here for the documentation on the getElementById method showing that it only accepts a single ID parameter: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Relatively new to JS/Ajax, so I may be missing something obvious here. Let's say at some point in javascript I run ajax to get a number of div elements with a certain class name. I then want to retrieve the html id tag from each of these elements and do something with that information (say populate the element), something like so.
var divstopop = document.getElementsByClassName("popField"),x;
for(x in divstopop){
divstopop[x].innerHTML= x.id; //x.id or something?
}
Is this in any way possible to do?
Using in is not how you should iterate over an array of elements. You should use the .length property and use numeric indexing:
for (var i = 0, n = divstopop.length; i < n; ++i) {
// get id property from element and set as innerHTML
divstopop[i].innerHTML = divstopop[i].id;
}
Why doesn't this work?
var row = document.getElementById(currentRow);
var otherRow = document.getElementById(targetRow);
row.cells[0] = otherRow.cells[0];
This works with
row.cells[0].innerHTML = otherRow.cells[0].innerHTML;
However, there are attributes attached to the cell which I also want to move over without having to manually recreate them.
Solution (Note: more is being done in my actual implementation, but this is the framework):
for (var i = 0; i < 4; i++) {
var copyTo = row.cells[i];
var copyFrom = otherRow.cells[i].cloneNode(true);
copyTo.parentNode.replaceChild(copyFrom, copyTo);
}
You should be able to use cloneNode() to actually clone the node and its attributes.
Each entry in cells refers to a DOMElement. When you typed row.cells[0] = otherRow.cells[0], you are saying that you want row.cell[0] to reference the same DOMElement as otherRow.cells[0].
I'm guessing you want row.cells[0] to have the same text or HTML as otherRow.cells[0]; in which case, the second code snippet will do just that, since you are actually modifying the DOMElement, and not just changing which DOMElement you are referencing.
In my code I have a function that accepts an array of JQuery collections and applies some code to each via a for-loop.
The problem is that as soon as I reference one it somehow becomes a HTMLDivElement instead of a collection object.
function vacant_now($timetables, now){
console.log("1:" + $timetables);//still fine
for (var i=0; i < $timetables.length; i++){
console.log("2:" + $timetables[i]);//problem is here
var $timetable = $timetables[i];
console.log("3:" + $timetable);
$timetable.find(".booking").each(function(){ ...
it's called like this:
vacant_now($page.find(".timetable"), now);
I'm stumped.
The jQuery collection array is an array of DOM elements.
Doing this: $('#myDiv')[0];
returns the same as: document.getElementByID('myDiv');
Solution:
Use $('.timetable').eq(index);
for (var i=0; i < $timetables.length; i++){
$timetables.eq(i);
}
Cheers
Using [i] on a jQuery object returns the dom element. If you want the jQuery object at a specific index use the .eq() function:
console.log("2:" + $timetables.eq(i));
Example - http://jsfiddle.net/8FeEf/1/
With jQuery you can use the .each method, and after you must 'jquerify' the object :
function vacant_now($timetables, now) {
$timetables.each(function() {
var $timetable = $(this);
});
}
A jquery collection is in fact an array of DOM elements.
You can also use a for, the syntaxe is a little bit more verbose.
In all case, you must jquerify the object.
Exemple : http://jsfiddle.net/FTcpD/
I'm looping through cells in a table row. each cell has a text box in it, and I want to take the value of the text box and push it onto an array.
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $(this).children('input')[0].val();
submitvals.push(val);
});
}
Theres more to the function, but this is all that is relevant. For some reason, when I run this code, I get "HTMLInputElement has no method 'val'." I thought that input elements were supposed to have a val() method in jQuery that got the value so this makes no sense. Am I missing something, or doing it wrong?
val() is a jQuery method. .value is the DOM Element's property. Use [0].value or .eq(0).val()....
.val() is a jQuery function, not a javascript function. Therefore, change:
var val = $(this).children('input')[0].val()
To:
var val = $(this).children('input:eq(0)').val()
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $($(this).children('input')[0]).val();
submitvals.push(val);
});
}
.val() is a jquery method. Using [0] returns the DOM element, not the jquery element
var val = $(this).children('input:first').val();
What I don't understand, is why none of the suggested syntaxes on this or other questions similar to this seem to work for me. I had to do trial and error and eventually had to use:
MySelectElement.value = x;
It also didn't help that the Visual Studio Intellisense suggestions offer a whole other range of unworking method names, such as ValueOf().