I've got some JS code here. Basically, I am trying to change the ID of an element to some value from a previous variable.
Here's what I got so far;
function() {
var colorarray = [ "RANDOMCOLOR_0", "RANDOMCOLOR_1", "RANDOMCOLOR_2" ];
var RANcolorarray = colorarray[Math.rsound(Math.random() * (colorarray.length - 1))];
document.getElementsByClassName('RANDOMCOLOR').setAttribute('id', RANcolorarray);
}
This code throws an error in Chrome for line 4: Uncaught TypeError: undefined is not a function which is weird because JsLint finds no errors.
I also tried using the other way to setting id's;
document.getElementsByClassName('RANDOMCOLOR').id = RANcolorarray;
However, although this method does not throw an error on chrome or jslint - it does not work at all after inspecting the element.. :/
Any ideas?
document.getElementsByClassName('RANDOMCOLOR') returns a list of DOM nodes (even if there's only one match) so you can't just call .setAttribute() on the list as the list doesn't have that method.
You can either get the first item out of the list and call .setAttribute() on that one or use a for loop to iterate through the list and call it on all of them. Of course, since you're setting the id, you should not be setting multiple elements to the same id, so I'll assume you just want one element:
document.getElementsByClassName('RANDOMCOLOR')[0].id = RANcolorarray;
Or, a little more safe:
var elems = document.getElementsByClassName('RANDOMCOLOR');
if (elems && elems.length) {
elems[0].id = RANcolorarray;
}
Related
I am trying to get a feedback from Selenium tests and closest I've come to solution was with:
driver.findElement(By.className('classname')).getText();
But to make it effective I have to find all Elements with same classname, so I tried changing it to:
driver.findElements(By.className('classname')).getText();
but I get an error:
TypeError: driver.findElements(...).getText is not a function
Any suggestions how to fix it or ideas for code with equivalent function?
The problem is that .findElements() returns a collection and .getText() doesn't work on a collection, only a single element. If you want the text from each element, you will need to loop through the collection and get text on each element inside the loop.
See this reference if you need more info on looping through a collection.
Since findElements returns a collection, you can use the map method to loop through the collection and get the text for all the elements.
let array_of_elements = driver.findElements(By.className('some_classname'));
//get the text from the elements in an another array
let text_of_elements = array_of_elements.map((array_of_text,index,array_of_elements)=>{
return array_of_text.getText();
});
Read about the map method here.
You can get Text Collection Using:
List<WebElement> findData = driver.findElements("******");
for (WebElement webElement : findData) {
String getValueofString = webElement.getText();
}
I have the following code written in my .js file:
var tiles = document.querySelectorAll(".tile");
var tileNumbers = ["one", "two", "three", "four"];
for(var i = 0; i < tiles.length; i++){
var num = Math.floor(Math.random() * tileNumbers.lenth);
tiles.classList.add(tileNumbers[num]);
tileNumbers.pop(num);
}
The .tile are 4 <div>'s in the .html file, and I am trying to add a class each of the four tiles separately. The classes are held in tileNumbers. When I run the code in Chrome I get the error:
"Uncaught TypeError: Cannot read property 'add' of undefined."
I am pretty sure everything is spelled correctly. Please help!
You want to call add on the tile, but try to access the add function of the tiles array itself. This does not exist.
What you need to do is to access the add function of each individual tile. To do so, first get it:
var tile = tiles[i];
Then, change your call to
tile.classList.add(…);
(You could also omit the temporary variable tile, and use tiles[i].classList.add directly. But IMHO using a dedicated variable makes the code more clear to read.)
Another option, which may be even better, is to use forEach. Since you use the i only for accessing the current element and nothing else, you basically want to perform an action on each element. You can do it like this as well (and, for bonus points, this even protects you against off-by-one errors):
tiles.forEach(function (tile) {
// ...
});
Then, within the function body, you automatically have a variable tile that you can access in the way you want to.
That's it :-)
tiles[i].classList.add(tileNumbers[num]);
Not
tiles.classList.add(tileNumbers[num]);
I'm playing around with .classList and I'm getting some odd errors in my console. Here's my demo
Basically, I have an array of images all with the class of child and I'm doing a javascrpt .querySelectorAll to store those images in a variable for further manipulation.
var el = document.querySelectorAll('.child');
console.log(el.classList;);
el.classList.add("someClass");
But when I open up my console I'm getting some errors .
This one in reference to .classList;
undefined
And this one in reference to .classList.add();
Uncaught TypeError: Cannot read property 'add' of undefined
Yet, when I switch to looking up elements by ID, the errors go away. Now using IDs isn't out of the question, but ideally I'd like to keep things to class Names. Any idea what's going on?
el is a collection, not a single DOM element. classList does not make much sense for an array, though. So what you might want to do:
var product = document.getElementsByClassName('product');
var el = document.querySelectorAll('.child');
for(var i = 0; i < el.length; i++) {
el[i].classList.add("someClass");
console.log(el[i].classList);
}
I have an error in the following code and I can't find why...
Using UiApp I define a couple of ListBox like this in a for loop
var critGlist = app.createListBox().setName('critGlist'+n).setId('critGlist'+n).addChangeHandler(refreshGHandler).addChangeHandler(cHandlerG).setTag(listItem[n]);
I added a TAG to be able to retrieve a value in the handler function because when I add items to this list I do it like this :
for(var c=0;c<listItem[n].length;++c){
critGlist.addItem(listItem[n][c],c);// the returned value is c, the value shown is listItem[n][c]
}
Then in my handler function I retrieve the value c that is the index of an element of the array listItem[n]
Since I stored a stringified value of this array as a tag I have to retrieve the tag first and then using the index I get the desired value...
That's where it becomes problematic !
I tried the 3 following codes :
var idx = Number(e.parameter['critGlist'+c]);// this works and I get the index
var item = e.parameter.critGlist0_tag.split(',')[idx];// this also works for a fixed index (0 here) but I need to use it in a for loop so I tried the code below
var item = e.parameter['critGlist'+c]_tag.split(',')[idx];// this generates an syntax error
// error message :"Signe ; manquant avant l'instruction. (ligne 129, fichier "calculatrice Global")"
// which means : missing ; before statement (line 129...
Am I missing something obvious ? How should I write it differently ?
Obviously it is the underscore that is not accepted... but how could I not use it ?
Well, I have a few other possibilities to get the result I want (using a hidden widget for example or some other temporary storage of even let the listBox return the value instead of the index) but still I'd like to know why this syntax is wrong ...
I'm not asking for a different code (as mentioned before there are a lot of other ways to go) , just some explanation about what is wrong in this code and this #!##å»ÛÁØ underscore ;)
You will need to put the whole property within the brackets as below
var item = e.parameter['critGlist'+c+'_tag'].split(',')[idx];// this generates an syntax error
I am working on a slider that uses jQuery. Some elements of the slider are working correctly, but there is a problem that I am trying to troubleshoot with some of the code. To test it I would like to be able to display the values of the variables in the statement.
Here is the code block I am working with:
$('.marquee_nav a.marquee_nav_item').click(function(){
$('.marquee_nav a.marquee_nav_item').removeClass('selected');
$(this).addClass('selected');
var navClicked = $(this).index();
var marqueeWidth = $('.marquee_container').width();
var distanceToMove = marqueeWidth * (-1);
var newPhotoPosition = (navClicked * distanceToMove) + 'px';
var newCaption = $('.marquee_panel_caption').get(navClicked);
$(' .marquee_photos').animate({left: newPhotoPosition}, 1000);
});
I added a div called 'test' where I would like to display the values of the variables to make sure they are returning expected results:
<div class="test"><p>The value is: <span></span></p></div>
For example, to test the values, I inserted this into the statement above:
$('.test span').append(marqueeWidth);
However, I don't get any results. What is the correct way to include a test inside that code block to make sure I am getting the expected results?
Thanks.
Just use JavaScript's console functions to log your variables within your browser's console.
var myVar = 123;
console.log(myVar, "Hello, world!");
If you're unsure how to open the console within your browser, see: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
append is used to append either an HTML string, a DOM element, an array of DOM elements, or a jQuery element. Since you are just trying to show a number (marqueeWidth), you probably want to set the text of the span instead:
$('.test span').text(marqueeWidth);
Also, is there a particular reason why you don't just use the console? It may be worth reading over a Debugging JavaScript walkthrough.
you can use the following.
$('.test span').html(marqueeWidth);
However doing a console.log(yourvariable); or alert(yourvariable); is better.