Friday, March 2, 2012

How to convert jquery object to string?

In jquery we can use .html() get the html code.
But how can we convert it to string?
That is very simple, we just asign the .html() to a javascript variable.

var v = $("#xxx").html();

The variable v will be change to a string that about .html() content.

DEMO


<html>
<body>
<div class="demo">
<h2>DEMO</h2>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function test(){
    var v = $("#asignHtmlToString").html();
    alert(v);
}
</script>
<button id="asignHtmlToString" onclick="test();">Click Me</button>
 </div>
</body>
</html>

Related Articles
jquery disable button

How to compare space with jquery?

Compare the space we can use unicode to comparing it.
the space unicode is 32.
<b> </b>

The below code show how to compare the space use jquery.
if( $("b").html().charCodeAt() == 32 ) {}

Click below demo button will show the alert popup when find the li tag have space.

DEMO


  • Text1
  • Text2

  • Text3

Below is the source code:
<html>
<body>
<div class="demo">
<h2>DEMO</h2>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function test(){
    $("li").each(function(e){
        if($(this).html().charCodeAt() == 32){
            alert("I have a space");
        }
    });
}
</script>
<ul> 
      <li>Text1</li>
      <li> </li>
      <li> </li>
      <li>Text2</li>
      <li></li>
      <li>Text3</li>
      <li>    </li>
</ul>
<button onclick="test();">Click Me</button>
</div>
</body>
</html>

Related Articles
jquery disable button