user76 user76 - 1 month ago 9
jQuery Question

Replace text part before element with JavaScript/JQuery

I have a given text with t-tags before some words. Inside the t-tags is the id of the word before the tag, which I have to find and replace with some html-code. What I have so far seems too complicated and also does not work, because the replaced html is printed as text and not as html.

Anybody an idea of a better, easier and working solution?

JSFiddle: https://jsfiddle.net/fsdx2o7h/18/

This is the first<t>element1</t>. This is the second<t>element2</t>. This is the third<t>element3</t>.




$('t').each(function() {
var prevText = this.previousSibling.nodeValue;
var arrPrevText = prevText.split(' ');
var nrElements = arrPrevText.length;
var textpart = arrPrevText[nrElements-1];
var id = $(this).html();
arrPrevText[nrElements-1] = "<span id='" + id + "'>" + textpart + "</span>";
this.previousSibling.nodeValue = arrPrevText.join(' ');
});




Answer

It can be a bit simpler, yes, but you were on the right track. See comments:

$('t').each(function() {
  // Get our previous sibling
  var prev = this.previousSibling;
  // If not a text node, quit
  if (prev.nodeType !== 3) {
    return;
  }
  // Get the text of it
  var text = prev.nodeValue;
  // Find the last word; if none, quit
  var index = text.lastIndexOf(" ");
  if (index < 0){
    return;
  }
  // Skip past the space prior to the word
  ++index;
  // Grab the word
  var word = text.substring(index).trim();
  // Remove it from the text node
  prev.nodeValue = text.substring(0, index);
  // Replace this `t` element with a span using
  // the word as its text and this `t` element's
  // innerHTML as its ID
  $(this).replaceWith(
    $("<span>").text(word).attr("id", this.innerHTML)
  );
});
span[id] {
  color: red;
}
This is the first<t>element1</t>. This is the second<t>element2</t>. This is the third<t>element3</t>.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>