Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare an html entity with jQuery

I have the following html code:

<h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3>

I would like to toggle between up arrow and down arrow each time the user clicks the span tag.

function expandCollapse(id) {   
    var arrow = $("#"+id+" span").html(); // I have tried with .text() too
    if(arrow == "&dArr;") {     
        $("#"+id+" span").html("&uArr;");               
    } else {        
        $("#"+id+" span").html("&dArr;");               
    }
}

My function is going always the else path. If I make a javacript:alert of arrow variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the arrow variable as a string and not as html.

like image 914
Sergio del Amo Avatar asked Aug 27 '08 12:08

Sergio del Amo


2 Answers

When the HTML is parsed, what JQuery sees in the DOM is a UPWARDS DOUBLE ARROW ("⇑"), not the entity reference. Thus, in your Javascript code you should test for "⇑" or "\u21d1". Also, you need to change what you're switching to:

function expandCollapse(id) {
    var arrow = $("#"+id+" span").html();
    if(arrow == "\u21d1") {     
        $("#"+id+" span").html("\u21d3");                           
    } else {            
        $("#"+id+" span").html("\u21d1");                           
    }
}
like image 80
jelovirt Avatar answered Oct 12 '22 10:10

jelovirt


If you do an alert of arrow what does it return? Does it return the exact string that you're matching against? If you are getting the actual characters '⇓' and '⇑' you may have to match it against "\u21D1" and "\u21D3".

Also, you may want to try &#8657; and &#8659; since not all browsers support those entities.

Update: here's a fully working example: http://jsbin.com/edogop/3/edit#html,live

window.expandCollapse = function (id) {   
  var $arrowSpan = $("#" + id + " span"),
      arrowCharCode = $arrowSpan.text().charCodeAt(0);

  // 8659 is the unicode value of the html entity
  if (arrowCharCode === 8659) {
    $arrowSpan.html("&#8657;");                           
  } else {            
    $arrowSpan.html("&#8659;");                           
  }

  // one liner:
  //$("#" + id + " span").html( ($("#" + id + " span").text().charCodeAt(0) === 8659) ? "&#8657;" : "&#8659;" );
};
like image 33
travis Avatar answered Oct 12 '22 10:10

travis