Reputation: 17831
I'm trying to manipulate some anchors after the document is loaded to alter their href attribute using Prototype. Based on the class of an anchor, its href has to be rewritten to be used by a tracking software.
I hacked some things together but can't quite figure out why it doesn't work. It always returns undefined, not matter what I search for.
<script type="text/javascript">
var elements = $$(".replace");
for (el in elements) {
el.href = "other_href.html";
}
</script>
<a href="this_href.html" class="replace">Link</a>
When I alert(el)
in the loop, it returns either undefined or (when I search for a.replace
an extraordinary number of elements that don't even exist on my page.
Where is my thinking error in here?
Upvotes: 0
Views: 909
Reputation: 219874
Untested:
<script type="text/javascript">
document.observe('dom:loaded', function() {
$$(".replace").each(function(a) {
a.writeAttribute('href', 'other_href.html');
});
});
</script>
<a href="this_href.html" class="replace">Link</a>
I'm guessing your JavaScript was loaded and executed before the HTML it was supposed to manipulate was loaded by the browser. It can't manipulate what doesn't exists yet. That's where observing events comes in handy. In this case, we're waiting for the DOM to finish loading, but before the page is rendered by the browser, to make our changes.
I also took advantage of Prototype's each()
functionality. It's a great way to loop through arrays and any enumerables. And writeAttribute()
is a good cross-browser way to modify element attributes.
Upvotes: 2