Edit document in document array from .find() - javascript

I need a way to get values and edit the values of an array returned by .find() example:
$container = $('#survey-types');
$slider = $container.find('#slide-container');
$slides = $slider.find('.slide');
for(let i = 0; i < $slides.length; i++){
console.log($slides[i].width());
}
But this gives me .width() is not a function

$slides[i] is an HTMLElement, not jQuery wrapper, and HTMLElement does not have a width() method. Try replacing $slides[i] with $slides.eq(i):
for(let i = 0; i < $slides.length; i++){
console.log($slides.eq(i).width());
}

You can also use the jQuery each() method, rather than writing your own for loop.
$slides.each(function(index, slide){
console.log($(slide).width());
//or you could still use eq
console.log($slides.eq(index).width());
});

Related

Javascript to Jquery for loops

I would like to convert these for loops into jQuery but I am unsure how to do this. I am also unsure of how to convert document.querySelector. I tried to convert it like this:
$('.table1 tbody')
but it does not work when you call
tablebody.row[]
This is my code:
var headertext = [],
headers = $(".table1 th"),
tablebody = document.querySelector(".table1 tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
Thanks
You can use map() to create an array from the attributes of the specified th elements. You can then loop through that array and set the data attribute on the required td elements.
That being said, you can change the logic entirely to do this in a single each() loop. Try this:
var $headers = $('.table1 th');
$('tr > td').each(function(i) {
$(this).data('th', $headers.eq($(this).index()).text().replace(/\r?\n|\r/, ""));
});
Working example
Note that jQuery keeps data attributes in an internal cache, so you won't see any changes to the DOM with the above code (which is why in the jsFiddle example I set the text() too). This is absolutely fine, you just need to remember to use jQuery's getter signature of data() to retrieve the attribute.
For your reference, your attempt to convert querySelector to $('.table1 tbody') didn't work because the jQuery version returns a jQuery object, not a DOMElement, and jQuery object's don't have rows property.
You can use each function in jquery to iterate over elements.
$('.table1 th').each(function(index){
var text=$(this).text();
});
And
$('.table1 tbody td').each(function(index){
var tdObject=$(this);
// loop for iterating over all the TDs of table.
// You can use tdObject to get text, class and other values.
// e.g. var id = tdObject.attr('id');
var text=tdObject.text();
});

document.getElementsByTagName not working

I would like to use document.getElementsByTagName('input')
to set as required (or unset it) for a list of inputs.
is it possible?
I've tried:
document.getElementsByTagName('input').required = false;
or (for a different purpose)
document.getElementsByTagName('input').value = ""
but it doesn't seem work.
Moreover: is it possible to catch a certain type of input (i.e. text or radio)?
Thank you!!!
ObOnKen
getElementsByTagName() returns a collection of elements so you need to iterate over the collection...
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++)
{
if(elements[i].type == "text")
{
elements[i].value = "";
}
}
getElementsByTagName() returns a live HTMLCollection. If you want to do something to each item returned, you'll have to explicitly iterate across them:
var inputs = table.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].required = false;
}
However, if you use some libraries, you may be able to operate on each of the contents of a collection (or, as some of the libraries call them, selection) en-masse with a syntax as you seem to expect.
You should use for loop for iterating all inputs, because document.getElementsByTagName returns a HTMLCollection of elements with the given tag name.
var values = document.getElementsByTagName('input');
for (var i = 0; i < values.length; i++) {
values[i].required = false;
}
To catch a certain type of input:
var textInput = document.querySelector("input[type=text]");
querySelector returns the first element within the document.

Using innerHTML with querySelectorAll

I want to use something similar to the following to clear errors in a form upon a resubmission attempt:
document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel, #form-error-dob, #form-error-password, #form-error-goal").innerHTML= "";
...But the contents of the divs isn't cleared. What am I doing wrong?
The question wants .innerHTML, but that's not valid on input; you actually want .value. The appropriate modern answer would be
[... document.querySelectorAll('input')]
.map(i => i.value = '');
You'll need to loop through the results
var errors = document.querySelectorAll(
"#form-error-name,
#form-error-email,
#form-error-tel,
#form-error-dob,
#form-error-password,
#form-error-goal");
[].forEach.call(errors, function(error) {
error.innerHTML = '';
});
querySelectorAll doesn't return an array, but a node list, which doesn't have a forEach method on its prototype.
The loop above is using the forEach method on the array object's prototype on the nodeList object.
Try this:
var x = document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel");
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = "";
}
See, if that helps.
Another way to do this is to call forEach directly on the results of querySelectorAll, which returns NodeList resutls:
query_selector = "#form-error-name, #form-error-email, #form-error-tel, #form-error-dob, #form-error-password, #form-error-goal"
document.querySelectorAll(query_selector).forEach(node => node.innerHTML = "")

Javascript : How to get multiple span elements by ID?

I have several span elements which begin with the same id as shown below...
<span id="graph_machine"
<span id="graph_human"
<span id="graph_custom"
I would like to access these 3 Span elements as an array in my Javascript function..
var elems = document.getElementsById("graph*");
But getElementsById does not support returning multiple values. Any suggestions? Perhaps using a different function and some wildcard?
Thanks.
Use document.querySelectorAll:
var elems = document.querySelectorAll("[id^=graph]");
That will return a node list of any element with an id attribute whose value starts with "graph".
Try to get all span ID and then check if span ID starts with "graph"
var spans = document.getElementsByTagName("span");
var graphSpans = new Array();
for (var i = 0; i <= spans.length; i++) {
if (spans.id.startsWith("graph")) {
graphSpans.push(spans[i]);
}
}
Since startsWith method is not available in Javascript, so you need to add it to prototype as soon document is ready.
jQuery(document).ready(function() {
if (typeof String.prototype.startsWith != 'function') {
// see below for better implementation!
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
}
If you are using jQuery you can use $( "span[id^='graph_']" )
You could get all spans and then check each ID individually:
var spans = document.getElementsByTagName("span");
var graphSpans = [];
for (var i = 0; i < spans.length; i++) {
if (spans[i].id.substring(0,5) === "graph") {
graphSpans.push(spans[i]);
}
}
http://jsfiddle.net/Sp6sp/
try this with jquery
$("span").each(function(){
console.log($(this).attr('id'));
});
Demo
http://jsfiddle.net/p5k2a/1/

I want to loop through an array and modify attributes

Here is my code
var input_buttons = ["#one","#two","#three"];
var substr = input_buttons.split(',');
for(var i=0; i< substr.length; i++)
{
substr.attr('value', '');
}
Why doesn't this work?
Your first problem is calling split(',') on an array. However, if you just want to set the values of all those to a blank string you can do:
$('#one,#two,#three').val('');
If you want to set different values you'd need to loop through:
$('#one,#two,#three').each(function() {
// this == the HTML node (not a jQuery element)
this.value = someValue; // someValue would set outside
};
You already have an array, there is nothing to split, this only works on strings. You'd also have to pass the ID to jQuery before you can cal attr. In this case val is even better.
var input_buttons = ["#one","#two","#three"];
for(var i=input_buttons.length; i--;) {
$(input_buttons[i]).val('');
}
But shorter would be using the multiple selector:
$('#one, #two, #three').val('');
or if you already have the array, create a string by joining the IDs:
$(input_buttons.join(',')).val('');
I'm wondering why you are calling:
var substr = input_buttons.split(',');
By the nature of your input_buttons, you already have an array. All you should have to do is:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< substr.length; i++)
{
$(input_buttons[i]).attr('value', '');
}
var input_buttons = ["#one","#two","#three"];
$.each(input_buttons, function(idx, value) {
$(value).val('');
});
Or even better and shorter:
$('#one, #two, #three').val('');
You could also give those elements a common class name and then use this:
$('.className').val('');
your array contains just the id but not the actual object
try this
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
$(input_buttons[i]).removeAttr('value');
}
input_buttons is already an array - don't split it.
To use .attr you need it to be a jquery object, so call $(input_buttons[i]).attr
Try the following to remove an attribute:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
$(input_buttons[i]).removeAttr('value');
}
The reason your code does not work is in the overloading of jQuery functions. .attr('value', '') evaluates to .attr('value'), which returns the value of value as opposed to setting it. The reason is that '' evaluates to false.

Categories

Resources