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>")); }); 
4

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
@JosephMarikle, habit, mostly.
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

3 Comments

You can't use forEach on something that's not an array - something you would have figured out if you'd tested your code before posting it.
@Andy what about now?
Why don't you test it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.