Mike-S122
Mike-S122

Reputation: 219

Javascript: Add element to content before   and after <br>

I've been searching for days but I don't seem to find a way to add a tag to text within a <div>. A new separate tag should be added to the text before &nbsp; and before and after <br>.

The original HTML code looks this way:

<div id="my_div">
John Mike&nbsp;Smith Taylor<br>
Test Street 123<br>
00000&nbsp;FL&nbsp;Miami<br>
US
</div>

After applying Javascript/JQuery it should look this way:

<div id="my_new">
<a id="firstname">John Mike&nbsp;</a><a id="lastname">Smith Taylor</a><br> 
<a id="street">Test Street 123</a><br>
<a id="zipcode">00000&nbsp;</a><a id="state">FL&nbsp;</a>
<a id="city">Miami</a><br>
<a id="country">US</a>
</div>

I've tried appendChild to my_div but it opens and close the tag after the text, instead of adding the tag to the text inside the div.

Upvotes: 1

Views: 846

Answers (2)

KtorZ
KtorZ

Reputation: 869

You can use a RegExp with String.replace() to do the job.

function formatContent(content) {

    var ids = [
        "firstname",
        "lastname",
        "street",
        "zipcode",
        "state",
        "city",
        "country"
    ];

    var i = 0;
    function _format (match, nbsp, br) {
        return "<a id=\"" + ids[i++] + "\">" + (br || match) + "</a>" + (br && "<br>" || "");
    }

    return content.replace(/([\w\s]+&nbsp;)|([\w\s]+)<br>|([\w\s]+)/g, _format);
}

$(function() {
     $('#my_div').html(formatContent($('#my_div').html()));
});

See on JsFiddle: https://jsfiddle.net/ssvv7wrL/1/

Upvotes: 2

guest271314
guest271314

Reputation: 1

Try creating array of id's ids ; utilizing .split() with RegExp argument &nbsp;|<br> to create array of text text ; .map() to iterate array text ; .replace() to add id from ids , add <br> , &nbsp; back to el text , return array res containing text as html ; call .html() on #my_div with argument res

var ids = ["firstname"
          , "lastname"
          , "street"
          , "zipcode"
          , "state"
          , "city"
          , "country"];

var text = $("#my_div").html().split(/&nbsp;|<br>/).filter(Boolean);
var res = text.map(function(el, i) {
  return el.replace(/(\w+.*)/
         , "<a id=" + ids[i] + ">$1</a>" 
         + (i === 1 || i === 2 || i === 5 ? "<br>" : " "));
});

$("#my_div").html(res);

console.log($("#my_div").html());

/*
<a id="firstname">John Mike&nbsp;</a><a id="lastname">Smith Taylor</a><br> 
<a id="street">Test Street 123</a><br>
<a id="zipcode">00000&nbsp;</a><a id="state">FL&nbsp;</a>
<a id="city">Miami</a><br>
<a id="country">US</a>
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="my_div">
  John Mike&nbsp;Smith Taylor
  <br>Test Street 123
  <br>00000&nbsp;FL&nbsp;Miami
  <br>US
</div>

Upvotes: 0

Related Questions