It is not permissible to tear down a standing Masjid, even if it is old, simply for the sake of building a public library in its place. It is not permissible to build a public library in its place even if it is already torn down. What is obligatory is that it should be restored if it is old, and a Masjid should be built in its place if it is torn down, even if it is by selling some of it in order to fix the rest of it. This is because the fundamental principle regarding the Waqf (religious donation) is that it is not to be sold, given away as a gift or inherited. This is due to the Prophet's statement to 'Umar bin Al-Khattab, may Allah be pleased with him, when he wanted to give his wealth (land) in Khaybar away in charity:
"Give its foundation away (i.e.,the land) in charity:it should not be sold, given away as a gift or inherited, but its fruit may be spent(i.e.,sold for profit)." (Al-Bukhari no. 2764)"
Thus, this was a general clarification concerning all charitable donations. The scholars exclude from this the case where its benefits have ceased, or moving it to another place is more desirable, more beneficial and more suitable. In such a case, it is permissible to sell it or change it to another place. It has been related that 'Umar bin Al-Khattab wrote to Sa'd bin Abu Waqqas, may Allah be pleased with them, when it reached him that the Treasury in Kufah had been broken into,
"Move the Masjid that is at At-Tammarin and place the Treasury in the Qiblah of the Masjid. For verily there will always be someone praying in the Masjid."
This took place in the presence of the Companions and there was no opposition to it. Therefore,it was a consensus. Also, this is because it(the Masjid) will remain as a Waqf (trust), at least in its intent, when it is not possible to keep it in its (original) form. This is under the condition that the sale or exchange - in the situation of permissibility - is carried out under the authority of the Islamic ruler or his representative, as a protection for the Waqf and safeguarding it from any foul play. May Allah send blessings and peace upon Muhammad, his family and his companions.