document.getElementsByTagName not working - javascript

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.

Related

How to change the selectIndex of a selectBox in an HTMLCollection?

I'm trying to reset the values of all the selectBoxes on my page. The event in question is happening in an onClick so everything is loaded in the DOM.
I have obtained an HTMLCollection of selectBoxes via var selectBoxes = document.getElementsByClassName("selectBox"); I would like to now change the selectIndex of each of those selectBoxes to 0.
However, every time I try to access a property of a specific object from the HTMLCollection, I end up with an undefined value.
selectBoxes.item(0).selectedIndex = undefined
selectBoxes[0].selectedIndex = undefined
var selectBoxes = document.getElementsByClassName("filterBox");
console.log(selectBoxes); //a nice JavaScriptObject
for(i = 0; i < selectBoxes.length; i++){
selectBoxes.item(i).selectedIndex = 0;
}
This is a very interesting article on HTMLCollections: https://hackernoon.com/htmlcollection-nodelist-and-array-of-objects-da42737181f9 which seems to be explaining part of my problem.
I was accessing the selectedIndex property incorrectly. It's not a direct property of the selectBox itself but rather it seems to be inside the children of the selectBox.
var selectBoxes = document.getElementsByClassName("filterBox");
for(i = 0; i < selectBoxes.length; i++){
selectBoxes.item(i).children[0].selectedIndex = 0;
}

Javascript: Traversing through array and accessing its various elements?

Essentially what I'm trying to do right now is, given some input text, I split it up by white space and display on a
div id= "animation"
Every time a button is clicked, the array should go forward one word.
This is my current attempt.
function displayText() {
var displayText = document.getElementbyID("animation");
var list = (document.getElementbyID("input").split(/[ \tn]+/);
for (var i = 0; i < list.length; i++) {
displayText.innerHTML = list.get[i];
}
}
Is my thought process somewhat correct? For whatever reason, it doesn't seem to be working.
there are multiple issues in your method
function displayText() {
var displayTextAnimation = document.getElementbyID("animation"); //keep variable name and method name different
var list = (document.getElementbyID("input").value).split(/[ \tn]+/); //use value property and observe extra bracket
for (var i = 0; i < list.length; i++) {
displayTextAnimation.innerHTML = list.charAt(i); //observe replacing get by charAt
}
}

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/

Why is element.tagName undefined?

I was having a little play around this morning and I thought it would be fun to do something silly and try and write all the tagnames of a page on that page using something like this
var elements = document.getElementsByTagName("*");
for(var element in elements) {
document.write(element.tagName + "<br />");
}
However all that gets written is undefined. Why is this? Oh and I'm using Firefox.
for...in is not guaranteed to work for a NodeList (which is what document.getElementsByTagName() returns), and even when it does, what you'll be getting as the value of element will be not be a reference to the element but rather a property name, such as the numeric index of the element in the NodeList. Use a normal for loop instead.
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; ++i) {
document.write(elements[i].tagName + "<br />");
}
Also, document.write() won't work as you might expect after the document has loaded, which is when you'd typically use document.getElementsByTagName(). A better mechanism would be to populate an element in the page:
<div id="debug"></div>
Script:
var elements = document.getElementsByTagName("*");
var debugDiv = document.getElementById("debug");
var tagNames = [];
for (var i = 0; i < elements.length; ++i) {
tagNames.push(elements[i].tagName);
}
debugDiv.innerHTML = tagNames.join("<br>");
Because you're using a for...in loop, element is actually the item's key and not the value. elements[element] would give you the correct result, but you should use a proper for loop instead:
for (var i = 0; i < elements.length; i++) {
document.write(elements[i].tagName + "<br />");
}
This is because for...in may iterate over other enumerable properties that are not elements of the collection. These properties can differ between browsers.
You could try:
var elements = document.getElementsByTagName("*");
for (int i = 0; i < elements.length; i++)
{
document.write(elements.item(i).tagName + "<br />");
}
I suppose that is impossible, and is possible with jQuery/Sizzle HTML/CSS Selector:
$('*');
With that function/method you can only select "all available HTML tags" in your current document.
For example:
document.getElementByTagName('html');
document.getElementByTagName('head');
document.getElementByTagName('body');
document.getElementByTagName('h3');
document.getElementByTagName('p');
document.getElementByTagName('pre');
document.getElementByTagName('code');
document.getElementByTagName('metaforce'); // being a custom HTML(5) tag

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