Selecting the innerHTML of two <td>'s inside a <tr id="blahblahblah"> - javascript

Ok, so I've got an onclick event (CF-D07 is an example, these are generated programmatically based on a MySQL database):
<input type="checkbox" onclick="var nameUpdate = 'CF-D07';
datechange();" id="CF-D07">
So then, under datechange(), I have this:
function datechange() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(); }
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
// This section isn't done yet.
// var url = "changedate.psp"
// var params = "user=" + nameUpdate
// xmlhttp.open("GET", url + "?" + params,false);
// xmlhttp.send();
// xmlDoc=xmlhttp.responseXML;
}
The important part of this is this part of the code:
document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
How do I make it so that I get all of the elements with the tag, that then have the id of nameUpdate, based on the onclick event? And then after that, how do I select the innerHTML of the first two 's in the and put it into separate variables?

If I'm understanding you correctly, you should never have more than one element with the same ID on any page. If you need to classify html elements, use the class attribute.
To get the inner html of elements, you can use aptly named innerHTML property of the DOM element:
function datechange(nameUpdate) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
var trs = document.getElementByClassName(nameUpdate);
for(var i = 0, len = trs.length; i < len; ++i) {
var html = tr.innerHTML;
// Do what you need to with HTML
}
}
With the above code, your original HTML snippet could look like this:
<input type="checkbox" onclick="datechange('CF-D07')">
This also assumes you'd have a tr somewhere that looks something like this:
<tr class="CF-D07">
<td>...</td>
<td>...</td>
</tr>
To access the <td> elements of a given <tr>, you can use the children property for all child elements, or you can use getElementsByTagName directly on the tr element:
var tr = ... // get the TR somehow
var tds = tr.getElementsByTagName('td');
var allHTML = "";
for(var i = 0, len = tds.length; i < len; ++i) {
allHTML += tds[i].innerHTML;
}
// Do something with allHTML, which is the inner html of all tds put together

Related

Content Fetching from XML file

I have a xml content as below
<tty>
<xyz id="1">
<yzx>ghs</yzx>
<dfg>kli</dfg>
</xyz>
<xyz id="2">
<yzx>sss</yzx>
<dfg>ddd</dfg>
</xyz>
</tty>
I need to fetch the content of xyz also and when I try to do so I face an error stating
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "file.xml",false);
xmlHttp.send();
xmlDoc = xmlHttp.responseXML;
var wee= xmlDoc.getElementsByTagName("xyz");
for(var i=0; i<wee.length;i++){
var name = wee[i].childNodes[0].nodeValue;
var yzx = wee[i].childNodes[1].nodeValue;
var dfg= wee[i].childNodes[2].nodeValue;
error is
Cannot read property childnode
My output should have like below
name 1
yzx ghs
you are using getElementsByTagName twice :)
wee is already all of the <xyz> tags, and there are no more <xyz> tags below it. That means the getElementsBbyTagName('xyz') inside the for loop will return nothing.
You probably just want
for(var i = 0; i < wee.length; i++) {
var name = wee[i].childNodes[0].nodeValue; // "yzx" node
}
instead.

print entire xml data and tags in html - javascript [duplicate]

I want to convert an xml element like this:
<asin>​B0013FRNKG​</asin>​
to string in javascript
I used XMLSerializer:
new XMLSerializer().serializeToString(xml);
the string only shows on alert() and in the console. On the page it just says
[object Element][object Element]
I want to get the string.
You haven't told us how you go about displaying that object. XMLSerializer works on DOM nodes, so your object has to be added somewhere, for example:
document.getElementById('SomeDiv').appendChild(xml);
and if you just want the full xml string to be displayed:
var xmlText = new XMLSerializer().serializeToString(xml);
var xmlTextNode = document.createTextNode(xmlText);
var parentDiv = document.getElementById('SomeDiv');
parentDiv.appendChild(xmlTextNode);
<script type='text/javascript'>
function xmlToString(xmlData) {
var xmlString;
//IE
if (window.ActiveXObject){
xmlString = xmlData.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else{
xmlString = (new XMLSerializer()).serializeToString(xmlData);
}
return xmlString;
}
</script>
use this in case of IE for browser compatibility issues.
function getXmlString(xml) {
if (window.ActiveXObject) { return xml.xml; }
return new XMLSerializer().serializeToString(xml);
}
alert(getXmlString(xml));
Did you try enclosing the result like in…
(new XMLSerializer()).serializeToString(xml)
Also, I'd use console instead to see the content better:
console.log((new XMLSerializer()).serializeToString(xml));
If the DOM element <asin>​B0013FRNKG​</asin>​ is stored in the object element, then you can access the value using:
element.textContent
follow this to print,append data from xml data stored as string inside javscript
txt="<papers>"+"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<papers>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
x=xmlDoc.getElementsByTagName("paper");
for (var i = 0; i < x.length; i++) {
var athor =x[i].childNodes[0].firstChild.nodeValue;
var title = x[i].childNodes[1].firstChild.nodeValue;
var path = x[i].childNodes[2].firstChild.nodeValue;
var tack =x[i].childNodes[3].firstChild.nodeValue;
//do something with these values...
//each iteration gives one paper details
var xml=document.getElementById("element_id");//<div id="element_id"></div>
var li = document.createElement("br");// create a new <br>
newlink = document.createElement('A'); // creating an <a> element
newlink.innerHTML = athor;// adding <a>athor value here</a>
newlink.setAttribute('href', path);//
newlink.appendChild(li);// athor<br>
document.getElementById("element_id").appendChild(newlink);//finaly it becomes <div id="element_id">athor<br></div>
}

displaying xml data with javascript, issue at end of function?

Trying to make a text/sample page for a future project. I want to be able to list a certain amount of objects at a time from the xml document, with a button to load the next however many. Sort of like a browsing catalog. Here's what I got, and I'm pretty sure the problem is at the end of the listbythree function. I just don't know how to plug that function into the specified div element on pageload. any help?
<!DOCTYPE html />
<html>
<head>
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var i=0;
var x=xmlDoc.getElementsByTagName("book");
function listbythree()
{
for (i;i<3;i++)
{
document.write("<div style='display:inline;float:left;background-color:#ffff99;padding:10px;width:300px;height:210px;margin:5px;font-size:14px;'><img style='float:left;padding-right:4px' src=");
document.write(x[i].getElementsByTagName("cover")[0].childNodes[0].nodeValue + " />");
document.write("<em>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "</em><br/>");
document.write(x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br/>");
document.write(x[i].getElementsByTagName("pub")[0].childNodes[0].nodeValue + "<br/>");
document.write(x[i].getElementsByTagName("edition")[0].childNodes[0].nodeValue + "<br/>");
document.write(x[i].getElementsByTagName("genre")[0].childNodes[0].nodeValue + "<br/>");
document.write("Have I Read: " + x[i].getElementsByTagName("read")[0].childNodes[0].nodeValue);
document.write("</div>");
}
document.getElementById("booksbythree").innerHTML=this;
};
function next()
{
if (i<x.length-1)
{
i+3;
listbythree();
}
}
function previous()
{
if (i>0)
{
i-3;
listbythree();
}
}
</script>
</head>
<body onload="listbythree()">
<div id="booksbythree"></div><br/><br/>
<input type="button" onclick="previous()" value="<<" />
<input type="button" onclick="next()" value=">>" />
</body>
</html>
Your for loop only loops when i<3, so it will never show any elements further than the third. You can do the following to fix this. Also your next button is adding 3 to i when your for loop is also adding to i, this would make you skip 3 elements each time you click next.
function listbythree()
{
var j = i+3;
for (i;i<j&&i<x.length;i++)
{
....
}
}
function next()
{
if (i<x.length-1)
{
listbythree();
}
}
On a second note I would suggest that you use jQuery, it can make the AJAX and XML parsing much easier.

Syntax Error? When parsing XML value

I don't know if I'm having a syntax error but the compiler is giving me
TypeError: 'undefined' is not an object (evaluating
'xmlDoc.getElementsByTagName("icon")[count].childNodes')
Its me giving me this problem when im parsing the XML from my server, my actual javascript code is like this
var xmlDoc = Obj.responseXML;
var count = 0;
if(xmlDoc){
while(count <= xmlDoc.getElementsByTagName("item").length){
document.getElementById("flow").innerHTML += "<div class='item'><img class='content' src='" + xmlDoc.getElementsByTagName("icon")[count].childNodes[0].nodeValue.replace(/\s+$/g,' ') +"' /></div>";
count++;
}
}else{
alert("Unable to parse!");
}
and my XML goes like this.
<feed>
<item>
<title>Given Title</title>
<icon>
http://i178.photobucket.com/albums/w255/ace003_album/Logo-ETC-RGB-e1353503652739.jpg
</icon>
</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</feed>
i just want to parse the image link and to show it.
DOM parser
var url = "http://myURL.com/document.xml";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else
{
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
Obj.open("POST",url,false);
Obj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Obj.send();
Demo
Firstly, you're while loop condition should be just < not <=. By using the latter, the loop is running one too many times, causing the error because the index is out of bounds.
Secondly, in the while loop you're getting the icon elements based on the count from the root of the document. The icon's are children of each item so you should retrieve the icon relative to the item by using item.getElementsByTagName('icon')[0] not xmlDoc.getElementsByTagName('icon')[count].
Not related to the problem but building HTML as strings like that is undesirable. Creating the elements and inserting them into the DOM would be better because you don't need to handle any escaping. Also, store a reference to flow before the while, instead of finding it on each iteration.
var div;
var img;
var flow = document.getElementById('flow');
var items = xmlDoc.getElementsByTagName("item");
while(count < items.length){
div = document.createElement('div');
div.className = 'item';
img = document.createElement('img');
img.className = 'content';
img.src = items[count].getElementsByTagName("icon")[0].childNodes[0].nodeValue.replace(/\s+$/g,' ');
div.appendChild(img);
flow.appendChild(div);
count++;
}

Getting getElementById is Undefined

Here's my code:
<html>
<header>
<title>Checkup Date</title>
<script type="text/javascript">
function datechange() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(); }
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
var tr = getElementsById(nameUpdate)
var tds = tr.getElementsByTagName('td');
var user = "";
var date = "";
for(var i = 0, len = tds.length; i < len; ++i) {
user = tds[0];
date = tds[3];
}
var url = "changedate.psp"
var params = "user=" + user + "&date=" + date;
xmlhttp.open("GET", url + "?" + params, true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
</script>
</header>
<body>
<%
Python that doesn't matter
%>
<%= More Python %>
</body>
</html>
My outputted HTML:
<tr id="TL-D03">
<td>nobody</td>
<td>TL-D03</td>
<td>2010-01-01</td>
<td>
<input type="checkbox" onclick="var nameUpdate = 'TL-D03'; datechange();">
What am I doing wrong here? It says getElementById is undefined.
getElementById is a function of document:
var tr = document.getElementById("nameUpdate")
MDN: https://developer.mozilla.org/en/DOM/document.getElementById
Problem 1: you're calling getElementsById. IDs are unique: the function is getElementById. No s.
Problem 2: getElementById is not a global function. You need to call it on the document object:
var tr = document.getElementById(nameUpdate)
After all, your script could reference more than one document (for example, with an iframe), so you need to be explicit about where you expect the element to be.
Also try changing:
<input type="checkbox" onclick="var nameUpdate = 'TL-D03'; datechange();">
to this:
<input type="checkbox" onclick="datechange('TL-D03')">
and
function datechange() {
to this
function datechange(nameUpdate) {
makes more sence
It's document.getElementById(), not getElementsById(), as it only returns one element.
The latter would not be very useful, since id attributes must be unique within an HTML document.
you need to use document.getElementById("yourelementid")
The reason it doesn't work is that var scopes a variable to the function it is defined in, so it isn't readable outside the anonymous function assigned to the onclick handler.
In more general "wrongness" terms, passing data about using globals is generally a bad idea.
Pass it as an argument instead.
function datechange(nameUpdate) {
and
datechange('TL-D03');

Categories