1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.