I am writing a script that copies the href attribute from a link that is generated by another script upon page load and inserts that value into an anchor element that I then want to append to the original link’s parent. Just using jQuery to grab it in $(document).ready fails, returning 2 (as expected as I know there should be 2) empty objects. So, naturally I wanted to write a script that checks every second for the data and then, when it finds it, do the aforementioned actions and then exit the loop. I created the following script successfully, but I need a way to exit the loop if something goes wrong and the data never shows. So, in testing, I came across an error I could not figure out. Here is the code I’m working with:
$(document).ready(function(){
//the counter that will exit the loop at cnt == 10
var cnt = 0;
(function() {
//eliminate scope issues?
var THIS = this;
//should be array of two anchors
var link = $('.headline > a');
//the insurance
//if (cnt == 10) {console.log(cnt);return;}
if (link.length > 0) {
//to begin i just wanted to grab the first href attribute
var href = $(link[0]).attr('href');
if (href.length > 0) {
console.log(href);
} else {
//cnt++;
setTimeout(THIS, 1000);
}
} else {
//cnt++;
setTimeout(THIS, 1000);
}
})();
});
The above code works (with the cnt references uncommented), but to test my counter, I changed “href.length > 0” to “href.length < 0” where this line appears in a conditional to force it to fail every time. I then wanted to log the counter to make sure it reached 10 before exiting. When I make this change, I get an error. The error I receive in FF’s console is “missing ] after element list. [object Window].” In Googling, I guess the length method executes the toString method so maybe calling that method on an empty object is causing the problem? Though I also tried to add a condition
if (typeof(href) == 'string' && href.length < 0) { ... }
and of course it didn’t work, giving me the same error. I could just ignore this issue because the original script DOES work, but this loose end makes me uncomfortable. What am I missing? :injured: