Question: So let's say I have some basic code
<a name = "sec">this is a test</a>
I want a javascript function to on click of a link to change that to
So user clicks: link!
And the JS kicks in to change the 1st html to:
<font color = "green"><a name = "sec">this is a test</a></font>
Is it possible to do this in JS?
Question: So let's say I have some basic code
<a name = "sec">this is a test</a>
I want a javascript function to on click of a link to change that to
So user clicks: link!
And the JS kicks in to change the 1st html to:
<font color = "green"><a name = "sec">this is a test</a></font>
Is it possible to do this in JS?
Share Improve this question asked Nov 8, 2011 at 22:20 facebook-1389780026facebook-1389780026 711 gold badge1 silver badge2 bronze badges 5 |5 Answers
Reset to default 8You can set the element's color with JS as a simple solution. You should also give the element a valid href attribute that nullifies the default click behavior.
<a name="sec" href="javascript:void(0);" onclick="this.style.color='green';">
this is a test
</a>
Try something along the lines of
<a href="#" onclick="this.style.color='green'; return false;">link</a>
And you should not use <font>
tag for setting text attributes, this is considered bad practice in today’s HTML (be it XHTML or HTML5).
Something like this should work: (Psudeo Code)
<a id="sec" onClick="makeGreen()">this is a test</a>
<script type="text/javascript" charset="utf-8">
function makeGreen() {
document.getElementById('sec').style.color('green');
};
</script>
Realistically, you should keep your semantics and your style separate. As other users have suggested, use a css class instead of modifying styles directly. This is fairly easy to do, as shown by this jsFiddle
<a href="#" id="my-link">This is a test</a>
<script type="text/javascript">
var el = document.getElementById('my-link');
el.addEventListener('click', function() {
this.className = 'clicked-class';
});
</script>
And of course in your CSS you would define some sort of rule:
.clicked-class {
color: green;
}
This could be made even simpler with a javascript library of your choice, but hopefully should be enough to get you started.
$(element).on("click",function() {$(this).css({'color', 'blue'});
<font>
not instead of JS – Quentin Commented Nov 8, 2011 at 22:25