0

here is a a link with text:

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

I want to delete nlinked after window loadend, here is js code:

    <script>
 window.onload = function() {
  var aEl = document.getElementById('linkk');
  aEl[0].href = "javascript:void(0)";
 };
 </script>

here is a example: https://geburtstagsplanet.com/allgemeinen/sfsdf-sd-d-d-fd/

but it doesn't work, why?

  • 1
    `getElementsByClassName` returns an array – Vlad274 Sep 14 '18 at 18:14
  • That is because your page has ` – zapl Sep 14 '18 at 18:25
  • @zapl how can do it? Must i change it to id? – Interessante Fakten Sep 14 '18 at 18:39
  • no, but when you use an id you can only change 1 element and you don't get an array returned, so ´elById.href` vs `elByClass[i].href`, `var els = document.getElementsByClassName('linkk'); for (var i = 0; i < els.length; i++) els.item(i).removeAttribute('href');` works for your page as it is for me. (see https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname - a `for in` loop fails) – zapl Sep 14 '18 at 19:01

4 Answers4

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

or

<srcipt>
 window.onload = function() {
  var aEl = document.getElementsByClassName('linkk');
  aEl[0].removeAttribute('href');
};
</script>
Arun Kumar
  • 885
  • 5
  • 11
0

document.getElementsByClassName() returns a collection of elements. You probably need to refer to a specific element in the collection. So

aEl.href

should actually be

aEl[0].href
Daniel
  • 1
  • 3
  • While your answer seems being technically correct it never mentions how to use the case like in the question with `aEl = document.getElementById('linkk')` correct. You might want to add that to your answer. – David Sep 14 '18 at 18:36
0

Firstly, your open script tag is misspelled. Should be <script> not <srcipt>

Secondly, getElementsByClassName returns an array. If you are trying to do this operation for all links, you need to iterate over the result:

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

Also, if you are using getElementsByClassName, you should update your HTML accordingly:

<a class="linkk" href="/allgemeinen/sfsdf-sd-d-d-fd/"><p class="posttt">blablabla</p></a>
Justin Pearce
  • 4,994
  • 2
  • 24
  • 37
0

Below code should work.

<script>
    window.onload = function() {
        const elem = document.getElementsByClassName('linkk');

        for( let i = 0; i < elem.length; i++ ){
            elem[i].href = '#';
        }
    }
</script>