Good evening,
I created a function to find the element with a unique propertyvalue. Now I like to access the element from outside the function. Whatever I do. it comes up empty.
Is there a solution?
Thanks Gerald
// Function to find element with unique propertyvalue for propertykey
function find_element(propertyKey, propertyValue) {
// Iterate through all elements in the model
$("element").forEach(function(element) {
// Find the property value at the given propertyKey
var value = element.prop(propertyKey);
if(value && value == propertyValue) {
console.log(" ", element);
return element;
}
});
}"
Hi,
you can't return from a forEach loop. Take a look here - https://medium.com/front-end-weekly/3-things-you-didnt-know-about-the-foreach-loop-in-js-ff02cec465b1
So you could do something like this:
function find_element(propertyKey, propertyValue) {
var found;
$("element").forEach(function(element) {
var value = element.prop(propertyKey);
if(value && value == propertyValue) {
found = element;
}
});
return found;
}
Hi,
Another option is to use your function as a filter, and then iterate on the resulting collection:
var propertyKey = 'some name';
var propertyValue = 'some value';
result = $('element').filter(function(el) {return el.prop(propertyKey) == propertyValue}); // result is a collection
// Show all results
result.forEach(function(el) {console.log(el)});
Regards,
JB