Javascript: setAttribute works, getAttribute fails

varrtto picture varrtto · Nov 13, 2013 · Viewed 12.6k times · Source

I have this code:

var object1 = getElementByID('obj1');
alert(object1.getAttribute('href'));

This displays correctly the URL in the href attribute of the object. But, when I try:

var object1 = getElementByID('obj1');
object1.setAttribute('href','someotherURL');
alert(object1.getAttribute('href'));

This fails. The code doesn't work on FF so I can only test it in IE, no Firebug =/. I have also tried.

object1.href = "someotherURL";

but it also fails. Does anyone knows why I cant modify the attribute? let me know if I need to provide more information.

Regards.

UPDATE: HTML:

<table class="msrs-topBreadcrumb" cellpadding="0" cellspacing="0" border="0" width="100%">
    <tr>
        <td>
            <span>
                <div>
                    <a href="SomeURL">A Name</a> &gt;
                    <a href="AnotherURL">A Name2</a> &gt;
                    <a href="Third URL">A Name3</a>
                </div>
            </span>
        </td>
        <td align="right">
            <span>
                <a href="URL1">A Name</a>&nbsp;|
                <a href="URL2">A Name2</a>&nbsp;|
                <a href="URL3">A Name3</a>&nbsp;|
                <a href="URL4">A Name4</a>
            </span>
        </td>
    </tr>
</table>

FUNCTION:

function mySubscriptions()
{
    var mySubsObj = getElementsByClass('msrs-topBreadcrumb')[0].firstChild.childNodes[0].childNodes[1].childNodes[0].childNodes[2];
    alert(mySubsObj.getAttribute("href"));
}

Answer

Guffa picture Guffa · Nov 13, 2013

Use document.getElementById and it works fine:

var object1 = document.getElementById('obj1');
object1.setAttribute('href','someotherURL');
alert(object1.getAttribute('href'));

Tested in Firefox, IE and Chrome.

Demo: http://jsfiddle.net/Guffa/zdrP9/