0

I need to convert a line of jQuery code to plain old JavaScript. Can someone guide me?

$('a').filter(function(index) {
    return $(this).text() === "Officer Title Equivalent*";
}).each(function() {
    $(this).html($(this).html().replace("*", "<span style='color:red'>*</span>"));
});
Athapali
  • 1,091
  • 4
  • 25
  • 48

2 Answers2

3

For a literal translation...

Grab the a elements.

var a = document.getElementsByTagName('a');

Use slice to coerce the nodelist into an array of nodes, then use the array methods filter and forEach

[].slice.call(a).filter(function (el) {
  return el.textContent === 'Officer Title Equivalent*';
}).forEach(function (el) {
  el.innerHTML = el.textContent.replace('*', '<span style="color:red">*</span>');
});

DEMO

The other option is what gurvinder hinted at in his question - no need for filter, just a conditional:

[].slice.call(a).forEach(function (el) {
  var txt = el.textContent;
  if (txt === 'Officer Title Equivalent*') {
    el.innerHTML = txt.replace('*', '<span style="color:red">*</span>');
  }
});

DEMO

And Joseph (comments) is right - you can also do:

[].forEach.call(document.getElementsByTagName('a'), function (el) {
  var txt = el.textContent;
  if (txt === 'Officer Title Equivalent*') {
    el.innerHTML = txt.replace('*', '<span style="color:red">*</span>');
  }
});

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
  • Nice answer. Is there a particular reason you chose to use `[].slice.call(a).forEach(function (el) { ...` instead of `Array.prototype.filter.call(a, function (el) { ...`? Is there a significant compatibility difference? – Joseph Marikle Dec 29 '15 at 19:23
  • Now that I look at it closer, you could even use `[].filter.call(a, function (el) { ...` in a similar vein to what you have already. – Joseph Marikle Dec 29 '15 at 19:28
  • @JosephMarikle, habit, mostly. – Andy Dec 29 '15 at 22:46
0

it should be as simple as

var allAnchors = document.getElementsByTagName( "a" );
for ( var counter = 0; counter < allAnchors.length; counter++)
{
   var node = allAnchors.item( counter );
   if ( node.innerText === "Officer Title Equivalent*" )
   {
      node.innerHTML = node.innerHTML.replace("*", "<span style='color:red'>*</span>");
   }
}

should work on most browsers

gurvinder372
  • 66,980
  • 10
  • 72
  • 94