Karolina Ticha
Karolina Ticha

Reputation: 531

Javascript refactoring - how to?

I have got table like this:

<table>
  <tr>
    <th>Name</th><td>Steve Martin</td>
  </tr>
  <tr>
    <th>Phone</th><td>XXX</td>
  </tr>
   <tr>
    <th>Bank account</th><td>654861/46147</td>
  </tr>
</table>

Im using JavaScript for same parts of my table. For example

$('th:contains(Name)').each(function(index) {
   var $this = $(this),
       dluh = $this.next(),
       dluhText = dluh.text(),
       dluhLink = $("<a />", {
         target: "_blank",
         href: 'www.google.com' + dluhText,
         text: dluhText,
         style: "text-decoration: none"
       });

   dluh.html('').append(dluhLink);
  });

Creates link from th elements. But on the other parts on my table I need to make link from td elements. For example:

$('th:contains(Phone)').each(function(index) {
   var $this = $(this),
       dluh = $this.next(),
       dluhText = dluh.text(),
       dluhLink = $("<a />", {
         target: "_blank",
         href: 'www.google.com' + dluhText,
         text: dluhText,
         style: "text-decoration: none"
       });

   dluh.html('').append(dluhLink);
  });

But most parts of code is the same. I think that I save same lines of code, but how to? Can you help me?

On CODEPEN I have got more code.

Upvotes: 1

Views: 50

Answers (1)

James Craig
James Craig

Reputation: 6854

You can save a lot of repetition with a function like this.

function addLink(selector) {
  $(selector).each(function(index) {
   var $this = $(this),
       dluh = $this.next(),
       dluhText = dluh.text(),
       dluhLink = $("<a />", {
         target: "_blank",
         href: 'www.google.com' + dluhText,
         text: dluhText,
         style: "text-decoration: none"
       });

   dluh.html('').append(dluhLink);
  });
}

Then call the function like this.

addLink('th:contains(Name)');
addLink('th:contains(Phone)');
addLink('th:contains(Bank account)');

JSFiddle

Upvotes: 3

Related Questions