0

I want to consolidate the following function into something more eloquent.

Basically I want to get element by id like "title#" and push "#" into the function so that if you click on title#x you will ReverseDisplay link#xcontent.

Appreciate any advice thank you.

document.getElementById("title1").onclick = function() {myFunction()};

function myFunction() {
     ReverseDisplay('link1content');
}

document.getElementById("title2").onclick = function() {myFunction1()};

function myFunction1() {
     ReverseDisplay('link2content');
}

document.getElementById("title3").onclick = function() {myFunction2()};

function myFunction2() {
     ReverseDisplay('link3content');
}

document.getElementById("title4").onclick = function() {myFunction3()};

function myFunction3() {
     ReverseDisplay('link4content');
}

document.getElementById("title5").onclick = function() {myFunction4()};

function myFunction4() {
     ReverseDisplay('link5content');
}

document.getElementById("title6").onclick = function() {myFunction5()};

function myFunction5() {
     ReverseDisplay('link6content');
}


document.getElementById("title7").onclick = function() {myFunction6()};

function myFunction6() {
     ReverseDisplay('link7content');
}

document.getElementById("title8").onclick = function() {myFunction7()};

function myFunction7() {
     ReverseDisplay('link8content');
}
Storm Brewer
  • 123
  • 6
  • 1
    This sounds like a job for classes, and not ids. Also in your example `function() {myFunction()}` is equivalent to `myFunction`. Edit: Also, your `myFunction` variable is being redefined multiple times, but since its a function declaration only the last one is used for all instances. – tcooc Sep 28 '16 at 14:48
  • 1
    For the question specifically, what does your html look like? – tcooc Sep 28 '16 at 14:51
  • what does `ReverseDisplay` do? – depperm Sep 28 '16 at 14:54

1 Answers1

1

You can use document.querySelectorAll():

const ReverseDisplay = x => console.log(x)

Array.from(document.querySelectorAll('[id^="title"]'))
  .forEach(el => el.addEventListener('click', () =>
     ReverseDisplay(`link${el.id.split('title').join('')}content`)))
<div id="title1">title1</div>
<div id="title2">title2</div>
<div id="title3">title3</div>

document.querySelectorAll() returns a NodeList, so we have to use Array.from() to be able to use array methods like forEach. Then we add a click event listener to each element using addEventListener() (see addEventListener vs onclick). Using split('title').join('') we remove the 'title' part from the ID and leave only the number. If you're wondering what are these ` and =>, see template literals and arrow functions.

Community
  • 1
  • 1
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177