Home > Software engineering >  How can I convert specific text to link within a div node?
How can I convert specific text to link within a div node?

Time:02-04

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 >John Smith current working on ticket LQ-1954</div>
    ... again, multiple locations ...
<div >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

  1. build the nodes back with the new links and
  2. replace it back into the same div?

CodePudding user response:

You can use .replace

document.body.outerHTML = document.body.outerHTML.replace(/(LQ-1954)/g , '<a> $1 </a>')

CodePudding user response:

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 >John Smith current working on ticket LQ-1954</div>
    ... again, multiple locations ...
<div >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 >John Smith current working on ticket LQ-1954</div>
    ... again, multiple locations ...
<div >Sally Jones <a href="[something]">assigned</a> GM-3398 yesterday</div> 

<button onclick="addLinks()">Add Links</button>

  •  Tags:  
  • Related