Reputation: 219
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
and before and after <br>
.
The original HTML code looks this way:
<div id="my_div">
John Mike Smith Taylor<br>
Test Street 123<br>
00000 FL Miami<br>
US
</div>
After applying Javascript/JQuery it should look this way:
<div id="my_new">
<a id="firstname">John Mike </a><a id="lastname">Smith Taylor</a><br>
<a id="street">Test Street 123</a><br>
<a id="zipcode">00000 </a><a id="state">FL </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
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]+ )|([\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
Reputation: 1
Try creating array of id's ids
; utilizing .split()
with RegExp
argument |<br>
to create array of text text
; .map()
to iterate array text
; .replace()
to add id
from ids
, add <br>
,
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(/ |<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 </a><a id="lastname">Smith Taylor</a><br>
<a id="street">Test Street 123</a><br>
<a id="zipcode">00000 </a><a id="state">FL </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 Smith Taylor
<br>Test Street 123
<br>00000 FL Miami
<br>US
</div>
Upvotes: 0