Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the innerText of an <a> using javascript

Tags:

javascript

When I click on the "show details" link it should change to "hide details". I tried the following code but it's not working:

out.print("<a href=\"javascript:parent.showHideDetails('"+id+"',this);\">show details</a>");

function showHideDetails(id,obj) {
    try
    {

        alert(obj.innerText);
        obj.innerText = 'hide details';
    }
    catch (err)
    {
        alert(err);
    }

}
like image 240
harishtps Avatar asked Jun 21 '11 14:06

harishtps


2 Answers

The problem is that this in your href attribute doesn't point to the anchor. You could pass an identifier there, and give the anchor element the same identified as id attribute; and then use document.getElementById to get the anchor.

Example:

out.print("<a href=\"javascript:parent.showHideDetails('"+id+"','anchor_1');\" id=\"anchor_1\">show details</a>");

function showHideDetails(id,identifier) {
    try
    {
        var obj = document.getElementById(identifier);
        alert(obj.innerText);
        obj.innerText = 'hide details';
    }
    catch (err)
    {
        alert(err);
    }
}
like image 86
Yhn Avatar answered Oct 05 '22 21:10

Yhn


The details in your question are sparse. Here are a few possibilities:

Remove parent. from the inline handler, and change it to an onclick:

"<a href=\"#\" onclick=\"javascript:showHideDetails('"+id+"',this);\">show details</a>"

Perhaps the showHideDetails() function isn't global

Perhaps innerText isn't supported in the browser you're using. Try innerHTML instead.

obj.innerHTML = 'hide details';
like image 42
user113716 Avatar answered Oct 05 '22 23:10

user113716