I’m trying to add the target attribute to some anchors when a radio button is checked; however it isn’t working.
Here is my code:
<body>
<ul id="main">
<li><a href="https://www.google.co.uk/">Google</a></li>
<li><a href="http://www.youtube.com/">YouTube</a></li>
<li><a href="https://twitter.com/">Twitter</a></li>
</ul>
<input type="radio" name="input" id="input" />
<script type="text/javascript">
document.getElementById('input').checked = function changeTarget() {
document.anchors.setAttribute('target', '_blank');
}
</script>
</body>
What am I doing wrong? (Note: I don’t want a JQuery solution)
Thanks.
Edit: Phew. Done it thanks to all the answers, here’s my final code:
document.getElementById('input').onclick = function changeTarget() {
if(this.checked) {
var b = document.getElementsByTagName('a');
for (a = 0; a < b.length; a++) {
b[a].target = '_blank';
}
}
}
With your edited code you set the targets every time to
_blankwhen clicking the radio button. Alsoanchors-collection is not the right-one to use in this case.document.linksis a collection-object containing theA-elements in the document which have anhrefornohref-attribute. A collection-object is quite similar to an array, and you can refer to it’s members with an index (n).