PDA

View Full Version : Change attribute of tags from Ajax retrieved content.


dipesh
03-26-2010, 08:15 AM
What I'm trying to do is retrieve the contents of the file shares.htm into a division of the file index.htm using AJAX, and then modify the attributes of the tags within the retrieved html.
But I have not been successfull in doing it.

Here's my index.htm which is the index file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
function go()
{
getContent('as','shares.htm');

var linx = document.getElementsByTagName('a');
var l=linx.length;
//alert(l);
for (var i = 0; i < linx.length; i++) {

if (linx[i].className == 'ss')
{

linx[i].setAttribute('href',(linx[i].getAttribute('href')+"&type="));
}
}
}

function getXmlHttp(){
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}

function getContent(id, file){
var xmlhttp=getXmlHttp();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",file,true);
xmlhttp.send(null);
}

</script>
</head>
<body onload="javascript:go();">
Hey
<div id="as"></div>

</body>
</html>

And this is shares.htm


<a class="ss" href="http://twitter.com/home?status=See this search - http://AskWhole.com/?search=" title="Click to share this site on Twitter" target="_blank"><img src="i/tw.jpg" style="border:none"/>Tweet this!</a>
<br />
<a class="ss" href="http://www.facebook.com/share.php?t=See this search&u=http://AskWhole.com/?search=" title="Click to share this site on Facebook" target="_blank"><img src="i/fb.jpg" style="border:none"/>&nbsp;Share on Facebook!</a>
<br />
<a class="ss" href="http://digg.com/submit?phase=2&url=http://AskWhole.com/?search=" title="Click to share this site on Digg" target="_blank"><img src="i/dg.jpg" style="border:none"/>&nbsp;Digg This!</a>
<br />


index.htm pulls shares.htm using AJAX and places its content in the division 'a'. The content is successfully replaced. I want to now change the 'href' attribute of all the 'a' tags with class 'ss'. The javascript for this particular purpose is written in the method 'go()' . It seems to work in Firefox if i decomment //alert(l); but not in other browsers.

The problem is:
document.getElementsByTagName('a') isn't getting the 'a' tags of shares.htm retrieved by AJAX.
What should be the solution?

Thanks in advance for your help.

Kor
03-26-2010, 10:28 AM
getContent() ?

dipesh
03-26-2010, 11:17 AM
getContent is the function i created that takes in two parameters.
The first one is 'id' and the second one is 'filename'.
It replaces the innerHTML of the element with id 'id' with the contents of the file 'filename'.