-2

I have this function:

function op_up(){
    this.style.color=#FF0000;
}

And I have this HTML element:

<span id="trigger" onClick="op_up(#element_1)">Click to change #element_1<span>
<span id="trigger" onClick="op_up(#element_2)">Click to change #element_2<span>

I would like the function to affect the id of the element in the onClick event.

Any help would be much appreciated. Thanks :)

ghipkins
  • 73
  • 1
  • 10
  • 4
    IDs are strings in JS, there is nothing special about how to pass them to a function. What is your question? Maybe you are looking for `document.getElementById(op_id)`? Or is `other_id` an implicit global variable holding an element with that ID? Then just use `op_id` inside the function instead of `this`. FWIW, `this` wouldn't work either anyway. – Felix Kling May 07 '14 at 22:24
  • +1 to what @FelixKling mentioned. Except that OP might want to use `document.getElementById(other_id)`. – bits May 07 '14 at 22:26
  • I am trying to pass the ID, `other_id`, from the onClick event to the function. – ghipkins May 07 '14 at 22:29
  • 1
    @AlfredPersonMc: It seems you are already doing that, `op_up(other_id)`. Maybe you have to pass a string instead, `op_up('other_id')`, but it's really not clear form the little explanation you provided. You will likely get better help if you provide a complete example. See http://stackoverflow.com/help/mcve. – Felix Kling May 07 '14 at 22:36
  • Ok, I will re-word the question... – ghipkins May 07 '14 at 22:51
  • bear in mind that id's must be unique (not the parameter passed, but the element id) - in your HTML, your `span` divs have the same `id` – blurfus May 07 '14 at 23:12

1 Answers1

1

Your function call is not valid, but you can pass a string to the function:

op_up('#element_1')

Then you can use document.querySelector to get a reference to the element:

function op_up(selector){
    document.querySelector(selector).style.color='#FF0000';
}

Or as I already said in the comments, if you pass the ID as

op_up('element_1')

use document.getElementById:

function op_up(id){
    document.getElementById(id).style.color='#FF0000';
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Because you didn't setup the fiddle correctly and because the color has to be in a string as well. Copied and pasted your mistakes :P See http://stackoverflow.com/q/17512582/218196 – Felix Kling May 07 '14 at 23:16
  • As I said, either you haven't put the color in a string or you didn't change the jsfiddle to put the function in the head or body. See: http://jsfiddle.net/p9rp6/1/ – Felix Kling May 07 '14 at 23:20