Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to check through the elements of the website for my code, but I can't understand how to do it with puppeteer on Node.JS
Here's the code I tried:
if(page.content('input[data-kwimpalaid="1580983806648-1"]'))
found = true
if(found = true)
console.log("I found it")
if(found = false)
console.log("I didn't found it")
So what I need basically, I have a website with element ID's ending in 1 to 20, and it can be random, and consecutive. For example it may start at 1, then has 6 ids (1,2,3,4,5,6) or it can start at 5 (5,6,7,8,9,10). I want to check for every ID, and if it exists then change the value of ''found'' to true. If the page doesn't have id 1, try id 2, id 3, id 4, etc.. until it finds an input with that ID/CLASS that exists on that website.
Shortly, I need to check if the selector element I use exists on the website or not (content).
Hm, what about this? On top of my head!
let found = false;
const allInputs = page.content('input[data-kwimpalaid]'); // Assuming an Array of elements here
for (let i = 1; i < 6; i++) {
if (allInputs.find((input) => input.dataset.kwimpalaid.startsWith(i))) {
found = true;
break;
}
}
if (found) {
console.log("I found it");
} else {
console.log("I didn't found it")
}
So basically scan the document once for all elements with an ID.
Then look at each element individually.
The for-loop respects your preference.
If an element is found Array.prototype.find will return it. Otherwise, its return value is undefined.
I'm assuming here, that puppeteer behaves similar to DOM in browser. Someone else might correct me, if that isn't the case.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I came across this piece of code which checks if number of occurrences of an element in an array is greater than it is specified, and if yes it will remove the number:
function deleteNth(arr,x) {
var cache = {};
return arr.filter(function(n) {
cache[n] = (cache[n]||0) + 1;
return cache[n] <= x;
});
}
But I didn't understand the code from here: arr.filter(function(n){cache[n] = (cache[n]||0) + 1;return cache[n] <= x;});
Can anyone please explain in simple words what happens here and how does cache[n] part work.
Why is cache[n] incremented?
Thanks!
The arr.filter() begins by iterating over each item in the array and this case each item is represented by 'n'.
This item is then added to the empty object where 'n' is the key and the value is then incremented by one for each new item added to the object.
The return statement uses the cache to do a check of what 'n' values are less than or equal to x. If it returns false they are not added into the new array that is created. So if 'x' is 3 it will remove everything after the first three items from the array.
EDIT
Another way of writing the function which might make it more clear could be
function deleteNth(arr,x) {
return arr.filter((item, index) => {
if (index <= x) {
return item;
}
});
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a collection in Javascript/Typescript
[
{"order":1,"step":"abc:","status":true},
{"order":2,"step":"xyz","status":true},
{"order":3,"step":"dec","status":false},
{"order":4,"step":"pqr","status":false},
{"order":5,"step":"tuv","status":false}
....
];
I need to write a function that every time its called it identifies the first occurrence of a false (Order:3 in the above example) and updates it to true. If the above method is called again now the next element (order:4 ) would have been updated. The steps that are false will always be below steps that are completed i.e true.
What's the best way (simplest, less code and elegant) to write this function? I can manually loop through using for each of the items in the collection, check for the first occurrence of false and then update it.
In ES6 you can use this:
yourArray.find((element) => !element.status).status = true;
See find() and its compatibility table.
And note that this will fail if there is no entry with status: false. A quick and dirty fix could for example look like the one below. But that entirely depends on your use case.
(yourArray.find((element) => !element.status) || {}).status = true;
Pretty much what you described is how you would do it:
for (let order of orders) {
if (!order.status) {
order.status = true;
break;
}
}
When you look for the matching occurance you require, then insert a 'break' statement to stop the search.
Example:
for( var i=0; i<recs.length; i++ ) {
if ( recs[i]['status'] == false ) {
recs[i]['status'] = true;
break;
}
}
You can use Lodash find method to find the first occurence of false status.
Sample Code
_.find(users, function(object) { return object.status === false });
lodash find documentation link
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have written the following JS, and it gets the job done, but I have been having a ton of trouble eliminating the repeating code. I keep breaking the functionality.
It's just field validation using a regex, and adding an error message below the appropriate field if the input doesn't match the regex. It's works, but but I really want to begin writing more succinct code.
If someone can help me do this, I can compare mine and yours and start understanding how to approach this type of task.
Thanks.
<form></form>
Here's my JSFiddle code: https://jsfiddle.net/robinburrage/cnL2d4w8/2/
You can reuse the same function for all the 2 validations. The only difference between the 3 functions is that you are trying to append to a different id.
Use this instead of referring to the element specifically, since the input is anyways bound to the element you are looking for.
phone.addEventListener('keyup', validatePhone);
phone2.addEventListener('keyup', validatePhone);
phone3.addEventListener('keyup', validatePhone);
function validatePhone(evt) {
var pattern = /^(\(\d{1,2}\)\s)?\(?\d{4}\-\)?[\s.-]?\d{4}$/; //set the regular expression
var str = this.value; //get the user's input
var phoneVal = document.getElementById("phoneVal");
if (phoneVal) { //if the error message div is already on the page
phoneVal.parentNode.removeChild(phoneVal); //remove it, to prevent a series of error message divs from accumulating
}
if (str === "") {//if there is no user input
phoneVal.parentNode.removeChild(phoneVal);//remove the error message
}
if (pattern.test(str) === false) { //if the string doesn't match the expression
var elem = document.createElement("div"); //create a DIV
elem.setAttribute("id", "phoneVal"); //give it an 1)id, 2)class and 3)message
elem.setAttribute("class", "form-error-msg");
if(window.location.href.indexOf("/en") > -1) {
elem.innerHTML = 'Please enter a valid telephone number.';
}else{
elem.innerHTML = 'Por favor introduce un número de teléfono válido.';
}
this.parentNode.appendChild(elem); //add the div with the current error message
}
} //end function
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am having a problem trying to change some innerHtml with this piece of code bellow:
var element = document.getElementByClass("productitemcell > a");
element.innerHTML = "Remover";
It is suposed to change the innerHTML from a link that says"Remove" to "Remover" and its not working.
Here's the page of it: http://ooleiro.businesscatalyst.com/OrderRetrievev2.aspx
You have to buy some products to access this shopping cart page.
I think you meant document.getElementsByClassName()
This method will return a HTMLCollection object. You can grab the first element like so:
var elements = document.getElementsByClassName('class');
var firstElement = elements[0];
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
The method is called getElementsByClassName (plural) and returns a collection of HTML elements. For which one of those do you want to change the HTML? For the first one?
Additionally, you cannot use a CSS selector like that in standard DOM methods
EDIT: Obviously you want to change all occurrences of a elements inside all occurrences of .productitemcell:
var pics = document.getElementsByClassName("productitemcell");
for(i=0; i<pics.length; i++) {
// loop over all elements with that class
var anchors = pics[i].getElementsByTagName("a");
for(j=0; j<anchors.length; j++) {
// loop over all anchor elements within the current class element
anchors[j].innerHTML = 'Remover';
}
}
Had to change the class to
var removerprod = document.getElementsByClassName("remover");
for(i=0; i<removerprod.length; i++) {
// loop over all elements with that class
var anchors = removerprod[i].getElementsByTagName("a");
for(j=0; j<anchors.length; j++) {
// loop over all anchor elements within the current class element
anchors[j].innerHTML = 'Remover';
}
}
so it doesnt change the product name as well. the only problem remaining is that it is retrieving with ajax and everytime it refreshes it changes again to "Remove"Thank's you devnul69, i realy learned a lot today about js.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello how can I add a second portion to my javascript. Here is the code:
var $pagerT = $('<div class="pager"></div>');
var $pagerB = $('<div class="pager"></div>');
for (var page = 0; page < numPages; page++) {
$('<span class="page-number"></span>').text(page + 1).bind('click', {
newPage: page
}, function(event) {
currentPage = event.data['newPage'];
$table.trigger('repaginate');
$(this).addClass('active').siblings().removeClass('active');
}).appendTo($pagerT).addClass('clickable');
}
Basically I want to add the same class that was added to $pagerT to $pagerB. Here is the code:
}).appendTo($pagerT, $pagerB).addClass('clickable');
Any subjections on how I can process it?
You can use .add
$pagerT.add($pagerB).addClass('clickable');
I'm going to say
var $pagers = $pagerT.add($pagerB);
...
}).appendTo($pagers);
$pagers.addClass('clickable');
The docs say that the argument to appendTo() can be an array of elements, and in that case, "cloned copies of the inserted element will be created for each target after the first".
(However I'm not sure if $pagerT.add($pagerB) creates an array (the doc says it creates a set); or more to the point, whether this value is acceptable as an argument to appendTo(). Testing this is left as an exercise to the reader.)
Or if you value brevity over maintainability,
...
}).appendTo($pagers.addClass('clickable'));
That's assuming that you want to add the <span> to both $pagerT and $pagerB (which you didn't say, but your second code example suggests) and add the 'clickable' class to both (which you said but which conflicts with your original code).