NOTE: The first requirement for this is that it not use jQuery.
I also do not want to use .innerHTML if I can avoid it (even if that requires a bit more code)
I have divs within a page (multiple locations) that will be something like this:
<div class="p-user-content">John Smith current working on ticket LQ-1954</div>
... again, multiple locations ...
<div class="p-user-content">Sally Jones <a href="[something]">assigned</a> GM-3398 yesterday</div>
There will be simple text, and tags like <a> mixed in with the text as shown.
The following script successfully identifies all the "text nodes":
var el = document.getElementsByClassName('p-user-content');
for (var i in el) {
if (typeof el[i].childNodes === 'undefined') continue
for (var k in el[i].childNodes) {
if (typeof el[i].childNodes[k] === 'function') continue
if (el[i].childNodes[k].nodeType !== Node.TEXT_NODE) continue
/**
This successfully gets the nodeValue
*/
console.log(el[i].childNodes[k].nodeValue)
}
}
What I want to do is split the text node word-by-word, and then convert values like LQ-1954 and GM-3398 to anchor elements, and then replace the modified text and anchor links back into the existing div. I'm able to split the text up and do the matching part, but how would I
You can use .replace
document.body.outerHTML = document.body.outerHTML.replace(/(LQ-1954)/g , '<a> $1 </a>')
If you must avoid manipulating html by changing the value of innerHTML,
create a new element and replace the old element with it:
function addLinks(){
var el = document.getElementsByClassName('p-user-content');
for (var i in el) {
if (typeof el[i].childNodes === 'undefined') continue
let value = el[i].innerHTML.replace(/[A-Z]{2}-[\d]{4}/g, (match)=>'<a href="#">' + match + '</a>');
let newDiv = document.createElement('div')
newDiv.insertAdjacentHTML("beforeend", value);
el[i].replaceChildren(newDiv)
}
}
<div class="p-user-content">John Smith current working on ticket LQ-1954</div>
... again, multiple locations ...
<div class="p-user-content">Sally Jones <a href="[something]">assigned</a> GM-3398 yesterday</div>
<button onclick="addLinks()">Add Links</button>
Simple way using innerHTML:
function addLinks(){
var el = document.getElementsByClassName('p-user-content');
for (var i in el) {
if (typeof el[i].childNodes === 'undefined') continue
el[i].innerHTML = el[i].innerHTML.replace(/[A-Z]{2}-[\d]{4}/g, (match)=>'<a href="#">' + match + '</a>');
}
}
<div class="p-user-content">John Smith current working on ticket LQ-1954</div>
... again, multiple locations ...
<div class="p-user-content">Sally Jones <a href="[something]">assigned</a> GM-3398 yesterday</div>
<button onclick="addLinks()">Add Links</button>