-2

I have a list of (at least 4) < a > tags with the class 'remove-typefilter' They do not have a 'href' ., but I want to give them all one when the users clicks a button.

This is the JS function I've written to achieve this:

function BuildButtons(urlparams) {
    elements = document.getElementsByClassName('remove-typefilter')
    for (let element in elements) {
        element.href = 'www.newlink.com' + urlparams
        element.style = 'color: red;'
    }
}

Yet when I run this function it does not change the attributs. The A tags get no link and the styling goes not change.

Does anyone know what I am doing wrong?

Jasper
  • 2,131
  • 6
  • 29
  • 61

4 Answers4

2

Two issues:

  • Syntax error in the function definition: url-params is invalid. Use urlParams.
  • for ... in loops iterate the keys of the iterated object, not the values. Use for ... of instead

Also:

  • Do not define elements as a global variable. Use const.
  • Better add a protocol in your URL, like http://
  • Although assigning a string to style works, it is more efficient to assign directly to the relevant style property

Corrected code:

function BuildButtons(urlParams) {
    const elements = document.getElementsByClassName('remove-typefilter');
    for (const element of elements) {
        element.href = 'http://www.newlink.com' + urlParams;
        element.style.color = 'red';
    }
}
trincot
  • 317,000
  • 35
  • 244
  • 286
2

you can set the href attribute by using the

Element.setAttribute(*name*,*value*);
1

for loops return the index not the actual element.

for (let element in elements) {

should be

for (let i in elements) {
    let element = elements[i];

or

elements.forEach(function(element) {
Buh Buh
  • 7,443
  • 1
  • 34
  • 61
0

Why not use querySelectorAll() and forEach()

function BuildButtons(urlparams) {
    var elements = document.querySelectorAll('.remove-typefilter'); 
    elements.forEach(function(element){
        element.href = 'www.newlink.com' + urlparams
        element.style = 'color: red;'
    });
};

BuildButtons('#xxx');  // invoke call the function how ever you like.
<a class="remove-typefilter">one</a>
<a class="remove-typefilter">two</a>
<a class="remove-typefilter">three</a>
caramba
  • 21,963
  • 19
  • 86
  • 127
  • 1
    This solved it, thanks! – Jasper Jan 24 '18 at 13:53
  • 1
    In my opinion there were other answers given before this one, that also *explained* what was wrong. – trincot Jan 24 '18 at 13:54
  • @Jasper https://stackoverflow.com/a/48423517/295783 is the more complete answer. – mplungjan Jan 24 '18 at 14:02
  • @Jasper I agree with mplungjan and trincot. `trincot`s answer should be the accepted one and not mine. His answer explains what you were doing wrong + why and how you can fix. My answer is just another approach on how you can solve the task you have. – caramba Jan 24 '18 at 14:24
  • Thanks for your responses, I've set trincots answer as the accepted one. – Jasper Jan 24 '18 at 14:56