Interessante Fakten
Interessante Fakten

Reputation: 49

How change href value after window is loaded

Here is an a link with text:

 <a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/"><p class="posttt">blablablabla</p></a>

JavaScript code to edit href property of all links

<script>
window.onload = function() {
    var aEl = document.getElementsByClassName('linkk');
    for(var link in aEl) {
        link.href = "javascript:void(0)";
    }
};
 </script>

Not working. Why? example: https://geburtstagsplanet.com/allgemeinen/sfsdf-sd-d-d-fd/

Upvotes: 3

Views: 59

Answers (3)

CodeMonkey
CodeMonkey

Reputation: 1156

If you for..in loop, change how you set the href.

if(aEl.hasOwnProperty(ele)) {
    aEl[ele].href = 'javascript:void(0)';
}

When you do the for..in loop, you are getting the key of the object returned by document.getElementsByClassName('linkk');, so using the key in this fashion gets you the value. Then you can set href.

Upvotes: 2

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can use a for..of loop over the Array created by Array.from(aEl):

window.onload = function() {
    var aEl = document.getElementsByClassName('linkk');
    for(var link of Array.from(aEl)) {
        link.href = "javascript:void(0)";
    }
};
<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/">
  <p class="posttt">blablablabla</p>
</a>
<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/">
  <p class="posttt">blablablabla</p>
</a>
<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/">
  <p class="posttt">blablablabla</p>
</a>
<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/">
  <p class="posttt">blablablabla</p>
</a>
<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/">
  <p class="posttt">blablablabla</p>
</a>
<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/">
  <p class="posttt">blablablabla</p>
</a>

Upvotes: 3

Jacob
Jacob

Reputation: 78890

Your for loop is wrong. The for..in loop is for enumerating the keys of an object, not items in an array. Replace your loop with:

var link;
for (var i = 0; i < aEl.length; i++) {
  link = aEl[i];
  link.href = "javascript:void(0)";
}

Upvotes: 5

Related Questions