WIndow.onload() not working on IE to hide table rows - javascript

window.onload = function(e){
cells = document.getElementsByName('assetID');
for(j = 0; j < cells.length; j++) cells[j].style.display = 'none';
cellsBMPartNo = document.getElementsByName('BMPartNo');
for(j = 0; j < cellsBMPartNo.length; j++) cellsBMPartNo[j].style.display = 'none';
defaultAssetTableValues();
}
I am simply hiding table rows by name.
See line 2 and 4 .
It works fine in Firefox but does not in IE.
Am I missing something ?

IE does not see elements added to the document dynamically (through the DOM) with getElementsByName. Are your elements created that way?
There are other problems with that method in different versions of IE. As a workaround, you could use getElementsByTagName('td') and then check to see if the name attribute matches the one you are looking for in a for-loop, iterating through the array of elements.
Here's a "IE-fixed" version of getElementsByName:
function getElementsByName2(tag, name) {
var els = document.getElementsByTagName(tag);
var arr = [];
for (var i = 0; i < els.length; i++) {
if (els[i].getAttribute("name") == name) {
arr.push(els[i]);
}
}
return arr;
}
And you would use it like so (for elements in table cells with name 'assetID'):
var cells = getElementsByName2('td', 'assetID');

I think the problem may be that <tr> and <td> elements really don't support a "name" attribute. IE doesn't complain directly, but its "getElementsByName()" function will not pay attention to elements like that.
You might want to use a "class" value instead.

IE could be looking for a name with assetID is you assetID defined in the name attribute?
as the others pointed out the name attribute is't for TD`s
ive noticed you have undeclared variables, cells, j, j, cellsBMPartNo also for one of the j's set one of those to i for example to make it easer to follow as well

Related

Change all ID values by same Class name

I am using the "Autofill" extention on Google Chrome which runs javascript codes. I want to change all ID's ctl01_ctl00_Main_Main_wtWeighted_txtWeight_xxxxx numeric values from 0 to 100 by same Class name weightBox Numeric.
My best guess was the code below but nothing.
document.getElementsByClassName('weightBox Numeric').value = "100";
getElementsByClassName() returns a live collection. In other words, it's a sort of array. So you have to loop through each value to change them. Also you can use querySelectorAll here:
var elements = document.querySelectorAll(".weightBox.Numeric");
for (var i = 0; i < elements.length; i++) {
elements[i].id = i + 1;
}

.each() add an attribute to a parent from jquery to js

I am a newbie in js and jquery and need help with rewriting my code from jquery to pure js.
I've got several parent divs. Each of them have a child div inside.
I want to add a class to both child and parent, but to parent as an attribute value in data-name.
Class names are stored in an array, in other words first parent and its child will get a array[0] class name, second parent and its child - array[1] class name, etc.
I use this jquery for this
$(".back").each(function(i) {
$(this).addClass(tile_array[i]);
$(this).parent().attr("data-name", tile_array[i]);
});
I tried to rewrite it in js like this:
var backs = document.querySelectorAll('back');
for (let i = 0; i < backs.length; i++) {
for (let j = 0; j < tile_array.length; j++) {
backs[i].classList.add(tile_array[j]);
backs[i].parentNode.setAttribute("data-name", tile_array[j]);
}
}
However, this does not work. How should I rewrite my code so that it works properly?
Thanks in advance!
try this : backs.length and tile_array.length are same .so no need ah inner loop
for (let i = 0; i < backs.length; i++) {
backs[i].classList.add(tile_array[i]);
backs[i].parentNode.setAttribute("data-name", tile_array[i]);
}
And add a class in querySelectorAll('.back')
You can skip the inner loop - you don't use it in your jQuery, why would you do that here?
Also, to set data attribute there is .dataset element property in Javascript. So your final code would be like:
var backs = document.querySelectorAll('back');
for (let i = 0; i < backs.length; i++) {
backs[i].classList.add(tile_array[i]);
backs[i].parentNode.dataset.name = tile_array[i]
}

Delete object by attribute in javascript

I have a few different tables on the same page but unfortunately they were not assigned any unique id's. I want to remove a table using a JS command, but since id cannot be used, is it possible to delete a table based on a certain attribute it has? For example, is there a command to delete all tables on the page that have the attribute: width="25%" ?
You can use querySelectorAll to do that.
var x = document.querySelectorAll("table[width='25%']");
for (var i=0; i<x.length; i++) { //returns array of elements that match the attribute selector
x[i].remove(); //call prototype method defined below
}
Removing is tricky, I found this code that makes a nice remove method
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
This creates a prototype remove() function that iterates the node and deletes the children.
Please note that querySelectorAll will not work in IE8 or below, but the poster of the prototype method said that it should work in IE8 but not 7.
I know this already has some solutions, but I'll offer up one more alternative.
var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++){
if(tables[i].getAttribute('width') == "25%"){
tables[i].parentNode.removeChild(tables[i]);
}
}
Demo at http://codepen.io/michaelehead/pen/HfdKx.
Yes you can. The easiest way is to use JQuery.
In your javascript code you would just write:
$("[attribute=value]").remove()
So in your case it could be something like $("table[width='25%']").remove()

For cycle or for each with js objects

I got a problem to add a onclick event to object who can be many times in same page
I am trying to
var i;
for (i = 1; i<=10; i++) {
var tmpObj='lov_DgId_D_'+i;
var tmpObj2=tmpObj.getElementsByTagName('a')[0];
if (tmpObj2 != null) {
tmpObj2.onclick= DgIdOnClick;
}
}
But got a error TypeError:
Object lov_DgId_D_1 has no method 'getElementsByTagName' , but this is working
lov_DgId_D_2.getElementsByTagName('a')[0].onclick= DgIdOnClick;
This ibject lov_DgId_D_ can be from 1 like lov_DgId_D_1 or lov_DgId_D_99 u.t.c
What wil be the best solution to add onclick to all lov_DgId_D_* objects ?
As you use jquery, the simplest is
for (i = 1; i<=10; i++) {
$('#lov_DgId_D_'+ i+ ' a').click(DgIdOnClick);
}
If you want to bind your event handler to all a elements inside elements whose id starts with lov_DgId_D_, then it's as simple as
$('[id^="lov_DgId_D_"] a').click(DgIdOnClick);
The problem you have is a confusion between the id of an element and the actual element. Some code that should work for you is this one:
var i;
for (i = 1; i<=10; i++) {
var tmpObj=document.getElementById('lov_DgId_D_'+i); // <-- here
var tmpObj2=tmpObj.getElementsByTagName('a')[0];
if (tmpObj2 != null) {
tmpObj2.onclick= DgIdOnClick;
}
}
Slightly easier to read code:
for (var i=0; i<=10; i++) {
var anchor = document.querySelector('#lov_DgId_D_'+i + ' a');
if (anchor) anchor.onclick = DgIdOnClick;
}
A note: this code attaches a click event to the first anchor (a element) inside each element with the id lov_DgId_D_n, with n being 1->10. Your original code seems to want to do the same thing.
Another note: usually when you iterate over elements using their id's to identify them, you are better suited to add a class to those elements instead. It provides for more maintaintable code and probably easier to understand as well.

how to access element whose id is variable

I need to access elements in html file using javascript, their names are like arr_1, arr_2, arr_3, I wish to use a loop to dynamically create the id then to access them like below:
for(var i=0; i< 10; i++) {
var id = "arr_" + i;
$document.getElementById('id')....
}
But it doesn't work. I remember there is an function to allow me do that, anyone know what that is?
You don't need the dollar sign preceding document, and you should pass your id variable to the getElementById function, not a string containing 'id':
for(var i=0; i< 10; i++) {
var id = "arr_" + i;
var element = document.getElementById(id);
// work with element
}
You might also want to check if getElementById actually found your element before manipulating it, to avoid run-time errors:
if (element) {
element.style.color = '#ff0000';
}
for (var i = 0; i < 10; i++) {
var obj = document.getElementById("arr_" + i);
obj.style.border = "1px solid red";
}
change
$document.getElementById('id')
to
$document.getElementById(id)
Since this question was published and answered quite correctly several times by using document.getElementById(id), another contender has entered the fray, querySelector, which takes any valid CSS selector and returns the first matched element.
Note that because querySelector takes a CSS selector, selecting an ID requires prefixing the ID with #.
for(var i=0; i< 10; i++) {
// Added the # here in the id variable.
var id = "#arr_" + i;
// assuming $document is a reference to window.document in the browser...
var element = $document.querySelector(id);
if (element) {
// do something with element
}
}
getElementById is typically faster than querySelector (in some browsers, twice as fast), which makes sense, since it doesn't have to invoke the CSS subsystem to find the element.
However, the option exists, and Stack Overflow is nothing if not thorough when answering questions.

Categories