0

    function diffSign(div) {
      var sign = document.getElementById(div.id);
      if (XXXXX) {
        XXXXX
      } else {
        XXXX
      }
    }
<div data-toggle="collapse" data-target="#demo@(i.tostring)" id="Sign@(i.ToString)" onclick=diffSign(this)>+</div>

I want to change + sign to - and can change back! THX

Jatin
  • 3,005
  • 6
  • 27
  • 42

5 Answers5

1

The function's div Argument is already representing this by reference.

jsBin demo

function diffSign(div){
    if (div.innerHTML === '+') {   // If has "+"
        div.innerHTML = '-';       // Set as "-"
    } else {                       // else? well...
        div.innerHTML = '+';
    }
}

Or you can do it also like: jsBin demo using bitwise XOR (^=) and Ternary Operator(?:)

function diffSign(div) {      
   div.innerHTML = (div.io^=1) ? '-' : '+' ; 
}

https://stackoverflow.com/a/22061240/383904

Community
  • 1
  • 1
Roko C. Buljan
  • 180,066
  • 36
  • 283
  • 292
  • 2
    Not worth a -1, but there's no reason to obfuscate your code like this. The comment you included doesn't really explain what the code does, either. – Jon Egeland Sep 30 '14 at 20:51
1
function diffSign(div) {
  var sign = document.getElementById(div.id);
  sign.innerText = (sign.innerText === "+") ? "-" : "+";
}

but if you pass in the div, why would you search it again?

function diffSign(div) {
  div.innerText = (div.innerText === "+") ? "-" : "+";
}

would work too if the div parameter is the real div... make sure this div has nothing other than the + or the - signs..

cheers.

Gal Schlezinger
  • 364
  • 1
  • 8
0

function diffSign(div) {
    var sign = document.getElementById(div.id);
    if (sign.innerHTML == '+') {
        sign.innerHTML = '-';
    } else {
        sign.innerHTML = '+';
    }
}
<div data-toggle="collapse" data-target="#demo@(i.tostring)" id="Sign@(i.ToString)" onclick=diffSign(this)>+</div>
Anton
  • 9,049
  • 11
  • 37
  • 66
0

Since div is the actual DOM element and a javascript object you can use it directly and add properties to it dynamically.

function diffSign(div) {
   //Add a new property to maintain the element's state on the first call, toggle it on subsequent calls
   div.useMinus = !div.useMinus;
   //set the text based on the current state.
   div.innerHTML = (div.useMinus ? '-' : '+');
}
Preston S
  • 2,682
  • 23
  • 36
-2

you can use document.getElementById.innerHTML = "your new text"........ to change text.