0

I have a text that must be send as an email. But to give the mail its layout we need to add some style. What we must do is the following: 1 find in a text one or more links with this format

<a href="RANDOM URL HERE">RANDOM TEXT</a>

2 change the links into this format:

<a href="RANDOM URL HERE" style="color: #FFFFFF; text-decoration: none;"><span style="color: #FFFFFF;">RANDOM TEXT</span></a> 

I have no idea how i can best do this, with regex or with DOM,...

Many thanks!

2
  • Why insert a span, when you already modify the style in a tag? Commented Apr 19, 2013 at 9:27
  • because some mail clients only look at the '<span>' tag, and some only look at the style in the '<a>' tag Commented Apr 19, 2013 at 9:55

2 Answers 2

1

First of all, you should consider never using regex for working with HTML/XML markup. You can read the reason here: https://stackoverflow.com/a/1732454/1249581 :)

Then, in order to answer the question you should do the following:

var div = document.createElement("div"),
    links;

div.innerHTML = textOfYourEmail;
links = div.getElementsByTagName("a");

for (var i = links.length; i--;) {
    var link = links[i],
        span = document.createElement("span");

    link.style.textDecoration = "none";
    link.style.color = "#fff";
    span.style.color = "#fff";

    while (link.firstChild) {
        span.appendChild(link.firstChild);
    }
    link.appendChild(span);
}

textOfYourEmail = div.innerHTML;

It uses embedded methods for DOM manipulation. It is fast and reliable.

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

Comments

0

In my opinion, the best way to do that is to create a css class and add it to your links. You do not need to add span tags! Using the DOM is the best way.

1 Comment

But it is for a text that will be used as an email, and email does not use css classes, it has to be inline

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.