How to change inner text <a> using javascript

When I click on the "show details" link, it should change to "hide details". I tried the following code, but it does not work:

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);
    }

}
+5
source share
4 answers

The problem is that thisin your href attribute does not indicate a binding. You can pass an identifier there and give the anchor the same attribute id; and then use document.getElementById to get the binding.

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);
    }
}
+6
source

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

Remove parent.from the built-in handler and change it to onclick:

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

, showHideDetails()

, innerText , . innerHTML.

obj.innerHTML = 'hide details';
+2

InnerText is one of those browsers that are named differently in different browsers. If you are just starting out with javascript, I would recommend using a framework like jQuery , because it is much easier to call a function like:

$('#linkID').text('show');   

The better to customize each browser option. Structure does it all for you.

+1
source

thiswill point to the DOM window, not the tag <a>. Therefore, use the onclickattribute to execute.

out.print("<a href=\"#\" onclick=\"showHideDetails('"+id+"',this);\">
show details</a>");
0
source

All Articles