May 27, 2011

Javascript innerText alternative for Mozilla Firefox


Since you are here i assume that you have already tried to work with innerText in cross-browser like mozilla firefox but you failed because in mozilla firefox the property innertext does not work. Don't there is an alternative method i will introduce in this javascript article or javascript tutorial. Before that i want to say something regarding innerHTML. Since most of the developers will suggest you to use innerHTML instead of innerText but my thought is different because if you use innerHTML instead of innerText then you may experience rendering problem due to your CSS. So i will suggest you use textContent instead of innerText for mozilla firefox will reslove your all problem. So first detect browser by javascript and then use innerText and textContent respecively like below:






Add an aspx page to test in your project. Copy and paste the below code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="innerText_textContent.aspx.cs" Inherits="innerText_textContent" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Alternative of innerText</title>
    
    <script type="text/javascript">
    function TransferValue()
    {
        var txtInfo=document.getElementById('<%= txtInfo.ClientID %>');
        var lblInfo=document.getElementById('<%= lblInfo.ClientID %>');
        if(document.all)
        {
            
            lblInfo.innerText = txtInfo.value;
        } 
        else
        {
            lblInfo.textContent = txtInfo.value;
        }
        return false;
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:TextBox ID="txtInfo" runat="server"></asp:TextBox>
    <asp:Button ID="cmdTransfer" runat="server" OnClientClick="return TransferValue();" Text="Transfer" />
    <asp:Label ID="lblInfo" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>




Run the page and you will get below interface:



No comments:

Post a Comment