0

I am trying to write a single function to change the text color that works on all p tags. If I have three p tags with different IDs, how would I write a function to get the ID from the element based on which one is clicked? I figure I need to set a variable to be equal to the ID of the element that was clicked, which is what I am struggling with. If there is an easier way I'd sure be open to that as well. Thank you very much for any help.

function changeColor() {

  var selected = document.getElementById('first');
  
  selected.style.color = 'red';

}
<p id="first" onclick="changeColor()"> First paragraph.</p>

<p id="second" onclick="changeColor()"> Second paragraph.</p>

<p id="third" onclick="changeColor()"> Third paragraph.</p>
pkc21
  • 27
  • 4
  • `onclick="changeColor(this)"` and accept the element on the method. Then you do not have to look anything up. – Taplar Jun 08 '20 at 19:59
  • 2
    I suppose here is the [answer](https://stackoverflow.com/questions/4825295/javascript-onclick-to-get-the-id-of-the-clicked-button) – vadimk7 Jun 08 '20 at 20:01

2 Answers2

0

Change it to something like this:

First paragraph. Second paragraph. Third paragraph.

Then handle the argument in the javascript: function changeColor(pClicked) { //Check which one was clicked and do something different here..

var selected = document.getElementById('first');

selected.style.color = 'red';

}

Zachucks
  • 148
  • 12
0

You can add a single event listener and look at the event's target to see what was clicked.

document.addEventListener('click', function(event) {
  if (!event.target.matches('p')) {return;}
  event.target.style.color = 'red';
  alert('my id is ' + event.target.id);
});
<p id="first"> First paragraph.</p>
<p id="second"> Second paragraph.</p>
<p id="third"> Third paragraph.</p>
Chase
  • 2,833
  • 10
  • 12