HTML Dom manipulation: IE7 issue - javascript

Why this sample of code doesn't work on IE7. Where is the problem? Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Test</title>
<script language="javascript" type="text/javascript">
function initialize()
{
for(var i=0; i < 10; i++)
{
var tab = document.getElementById("search").childNodes[0];
var line = document.createElement("tr");
var column = document.createElement("td");
column.appendChild(document.createTextNode("DATA"));
line.appendChild(column);
tab.appendChild(line);
}
}
</script>
</head>
<body onload="initialize()">
<div id="search" class="bulle"><table><tr><td></td><td align="right">X</td></tr><tr><td><table id="tableResult"><table></td><td></td></tr></table></div>
</body>
</html>

In IE you must add table rows to the tbody, not directly to the table. Also, in some browsers the first child of the div will be a text node if there is any whitespace between the DIV and TABLE tags in the markup. So either move the id to the table (or a tbody element), or use:
function initialize() {
var div = document.getElementById("search");
var tbody = div.getElementsByTagName('tbody')[0];
// create rows, cells, etc.
tbody.appendChild(line);
}
Note that all tables with rows will have a tbody element, even though the tags are optional in the markup (i.e. your markup doesn't have a tbody element, but the table in the DOM will have one).
There is a tutorial on MDN about using the DOM table methods: https://developer.mozilla.org/en/Gecko_DOM_Reference/Examples#Example_8:_Using_the_DOM_Table_Interface.

Related

elementNodeReference.children doesn't detect text nodes?

Per this link returns a list of child nodes. In my testing this seems to ignore text nodes. Is this correct?
What seems baffling to me is that firstChild works but the children list is zero.
Tested in Firefox 20.0.1.
Here's my test code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title></title>
<script>
function checktable() {
var mytable = document.getElementById("mytable");
var cells = mytable.rows[0].cells;
for (var i = 0; i < cells.length; i++) {
console.log("firstChild.nodeValue:", cells[i].firstChild.nodeValue);
console.log("firstChild.data:",cells[i].firstChild.data);
console.log("children.length:",cells[i].children.length);
}
}
function checkdiv() {
var mydiv = document.getElementById("mydiv");
console.log("firstChild.nodeValue:", mydiv.firstChild.nodeValue);
console.log("firstChild.data:",mydiv.firstChild.data);
console.log("children.length:",mydiv.children.length);
}
</script>
<style>
</style>
</head>
<body>
<table id="mytable">
<tr>
<td>Blob</td>
<td>Blab</td>
<td>Link</td>
</tr>
</table>
<div id="mydiv">
Blib
</div>
<button onclick="checktable()">Check table</button>
<button onclick="checkdiv()">Check div</button>
</body>
</html>
You want .childNodes, not .children.
The former is a method of Node and lists child nodes. The latter is a method of Element and consequently lists child elements, which is preferable in some situations.

Dynamically assign class to paragraph

How do you assign a class dynamically to a paragraph (via javascript/CSS) IF the paragraph contains the wording "Time Recorded:"?
You'll notice that I have manually assigned the paragraph with class class="dyncontent".
However, I'd like to dynamically assign this class to any paragraph tag which contain the words "Time Recorded:".
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">')
document.write('.dyncontent{display:none;}')
document.write('</style>')
}
</script>
<div class="right">
<ul>
<li class="say agent public">
<p>Description line 1</p>
<p class="dyncontent">Time Recorded: 5MIN(S)</p>
<p>Another description line</p>
</li>
</ul>
</div>
</body>
</html>
You could use jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(function(){
$("p:contains('Time Recorded:')").addClass('dyncontents');
});
</script>
$("p").each(function(ele) {if (this.html().indexOf('TimeRecorded') > 1) {$(this).addClass('dyncontent'))}});
I'd do indexOf because it will match easier than innerText
var allP = document.getElementsByTagName('p'),
pLength = allP.length;
while(pLength--){
if(allP[pLength].innerHTML.indexOf('Time Recorded') != -1){
allP[pLength].addClass('dycontents');
}
}
To explain: first you get all the <p> in the document. Then you loop through them. If any of them contain text of Time Recorded you add your class to it.
The following is solution without Jquery
o = document.getElementsByTagName('p');
for (i = 0; i < o.length; i++) {
if (o[i].innerText.indexOf('Time Recorded:') != -1) {
o[i].className = 'theClassYouWant';
}
}

Internet explorer and body onload

I have a page, where i'd like to use function. First a have a addTitle() function which is generated into a div. This is the function:
function addTitle(){
var ni = document.getElementById('div_fieldset');
var titleSpan = document.createElement("span");
ni.appendChild(titleSpan);
titleSpan.setAttribute("id","titleSpan");
titleSpan.setAttribute("class","fields");
if(titleSpan.previousSibling.nodeName=="#text"){
document.getElementById("titleSpan").style.paddingLeft="85px";
titleSpan.style.width="86.5%";
}else{
var titleSelect = document.createElement("select");
titleSelect.setAttribute("size","1");
titleSelect.setAttribute("name","titleSelect");
titleSelect.setAttribute("class","logicalOpSelect");
orOption=document.createElement("OPTION");
orText=document.createTextNode("OR");
orOption.appendChild(orText);
orOption.setAttribute("value","OR");
titleSelect.appendChild(orOption);
andOption=document.createElement("OPTION");
andText=document.createTextNode("AND");
andOption.appendChild(andText);
andOption.setAttribute("value","AND");
titleSelect.appendChild(andOption);
titleSpan.appendChild(titleSelect);
}
var titleSpanInner = document.createElement("span");
titleSpan.appendChild(titleSpanInner);
titleSpanInner.setAttribute("class","labels");
titleSpanInner.innerHTML="Title";
var titleInput = document.createElement("input");
titleSpan.appendChild(titleInput);
titleInput.setAttribute("class","input_text");
titleInput.setAttribute("type","text");
titleInput.setAttribute("name","title_input");
titleInput.setAttribute("size","50");
var removeButton = document.createElement("input");
titleSpan.appendChild(removeButton);
removeButton.setAttribute("id","removeTitle");
removeButton.setAttribute("class","removeButton");
removeButton.setAttribute("type","button");
removeButton.setAttribute("value","Delete field");
removeButton.setAttribute("onClick","remove(this.id)");
}
Then here is the html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<title>Search</title>
<link rel="stylesheet" href="css/search.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<script type="text/javascript">
function AddTitle(){
...
Here is the addTitle code, which is placed above
...
}
</script>
<body onload="addTitle();">
<div id="box">
<form name="search" method="post" action="search.php">
<div id="div_fieldset">
</div>
<input class="button" type="submit" value="Search">
</form>
</div>
</body>
</html>
And in internet eplorer 8 or 9 the field_set div has't any content, only the titleSpan span. But if i put the whole addTitle source into the field_set div, then the last section of the addTitle does'n appear, this one:
var removeButton = document.createElement("input");
titleSpan.appendChild(removeButton);
removeButton.setAttribute("id","removeTitle");
removeButton.setAttribute("class","removeButton");
removeButton.setAttribute("type","button");
removeButton.setAttribute("value","Delete field");
removeButton.setAttribute("onClick","remove(this.id)");
What is the problem and what is the solution? Thanks!

Javascript variable not refreshing in Phonegap application

I have just written my first app in phonegap that simply replaces a text string on the screen each time you activate a link.
The original string stays where it is and the new string is written over the top. If you then activate the link again the second string is replaced with a new one but still over the top of the first string.
I have tried clearing the variable to fix this but no luck.
Is this a platform limitation or am i doing something wrong?
Code is below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="newIdea()">
<h1 class="h1">First Love</h1>
<p>Have you ever? </p>
<h3><div id="ideaDiv">Nothing</div></h3>
Let's Do it
No Thanks
<script type="text/javascript">
var ideas=new Array(); // regular array (add an optional integer
ideas[0]="Kissed someone in the rain"; // argument to control array's size)
ideas[1]="Eaten peking duck";
ideas[2]="Stood naked in the open";
function newIdea(){
var idea = "";
var idea = ideas[Math.floor(Math.random()*ideas.length)];
var ideaSpace = document.getElementById("ideaDiv");
ideaSpace.innerHTML=idea;
var ideaLink=document.getElementById("ideaLink");
var linkCreate="http://www.google.com/calendar/event?action=TEMPLATE&text=" + idea + "&dates=20120101/20120102&details=&location=&trp=false&sprop=&sprop=name:";
ideaLink.href=linkCreate;
}
</script>
</body>
</html>
Thanks
Simon
I have no experience with phonegap, but in the past I found some problems trying to set innerHTML in xhtml documents, it don't check if the string you are using causes the document to still a valid xml and just throws an error, to achieve the same effect try:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="newIdea()">
<h1 class="h1">First Love</h1>
<p>Have you ever? </p>
<h3><div id="ideaDiv">Nothing</div></h3>
Let's Do it
No Thanks
<script type="text/javascript">
var ideas=new Array(); // regular array (add an optional integer
ideas[0]="Kissed someone in the rain"; // argument to control array's size)
ideas[1]="Eaten peking duck";
ideas[2]="Stood naked in the open";
function newIdea(){
var idea = "";
var idea = ideas[Math.floor(Math.random()*ideas.length)];
var ideaSpace = document.getElementById("ideaDiv");
//ideaSpace.innerHTML=idea;
ideaSpace.removeChild(ideaSpace.firstChild);
ideaSpace.appendChild(document.createTextNode(idea));
var ideaLink=document.getElementById("ideaLink");
var linkCreate="http://www.google.com/calendar/event?action=TEMPLATE&text=" + idea + "&dates=20120101/20120102&details=&location=&trp=false&sprop=&sprop=name:";
ideaLink.href=linkCreate;
}
</script>
</body>
</html>

selected text and xy coordinates

how to get a selected text and xy coordinates of the word in the same time??
Just googled it:
var txt = "";
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
// FireFox
txt = document.getSelection();
} else if (document.selection) {
// IE 6/7
txt = document.selection.createRange().text;
}
txt = txt.toString()
There is no simple way to get X/Y coordinates of the selected text. Because it dependes on its container position and size, text font, text layout, and many many other variables.
To expand on #MatuDuke's answer, you can get the position of the selected text like so:
var txt = window.getSelection(),
range = txt.getRangeAt(0),
boundary = range.getBoundingClientRect();
// Available positions:
// boundary.top
// boundary.bottom
// boundary.left
// boundary.right
These will give you pixel values relative to the viewport. However, it doesn't seem to work within text areas, a problem I'm currently trying to solve.
I am using this jQuery plugin http://plugins.jquery.com/node/7411 for a project and it seems to be working flawlessly. You could use jQuery to get the position of mouse http://docs.jquery.com/Tutorials:Mouse_Position
Here is some sample code I have worked on
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.textselect.js"></script>
<script type="text/javascript">
$(function(){
$('#select').bind('textselect click', function(e){
console.log(e.text);
console.log(e.pageX);
})
});
</script>
<!-- Date: 2010-11-05 -->
</head>
<body>
<div id="select">
This is a simple select test
</div>
</body>
</html>
You could try something like this
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.textselect.js"></script>
<script type="text/javascript">
$(function(){
$('#select').bind('textselect click', function(e){
console.log(e.text);
console.log(e.pageX);
var selected_text = e.text
var original_text = $(this).text();
var parts = original_text.replace(e.text, "/").split("/");
for(i in parts) {
console.log(parts[i])
}
})
});
</script>
<!-- Date: 2010-11-05 -->
</head>
<body>
<div id="select">
This is a simple select test
</div>
</body>
</html>

Categories