Sorry in advance for the extremely banal question, I'm positive I am missing something extremely simple. Without further adieu;
I'm getting a type error when I try to pull a block of text, and a button, from a div in my HTML. The div has an id that I am accurately referencing. For oversight, I am attempting to retrieve the text, apply coloring to each word (cycling through red, blue, and green), and replace the original text with my colored text. It works fine in JSFiddle, but I cannot get the data to retrieve in espresso - transcribeText is null.
var transcribeText = document.getElementById("divideTranscript");
transcribeText.onclick = function() {
var words = document.getElementById("transcriptText");
var textArray = words.innerHTML.split(" ");
var count = 0;
var colorArr = ["red", "blue", "green"];
var newWords = document.createElement("div");
for(var i = 0; i < textArray.length; i++){
var item = textArray[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.className = colorArr[count % 3];
newSpan.id = "word"+i;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
count++;
};
words.parentNode.replaceChild(newWords, words);
}
<div id="transcriptText"> It’s that time of year when you clean out your
closets, dust off shelves, and spruce up your floors. Once you’ve taken
care of the dust and dirt, what about some digital cleaning? Going
through all your files and computers may seem like a daunting task, but
we found ways to make the process fairly painless.</div>
<br>
<div id="divideTranscript" class="button"> Transform the
Transcript! </div>
Your problem is that the javascript runs before the HTML exists, therefore, you cannot get any ids. There are several ways around this. First is my favorite:
window.onload = function name() {
//code to be excuted
}
The function will be called after HTML has loaded. body.onload = function name() also works.
The second method (no pun intended haha) is to put the script tag at the end of the body tag.
<body>
<script></script>
</body>
Personally, I use the first one more commonly because I have a template I religiously use, and I don't like moving tags around. That's just me, whatever works for you! Hope this Helps!
Related
How do I output my current div element 100 times using a loop in the function written below? The way I try to do it does not output anything except the div element a single time.
function printHundredtimes()
{
for(i = 0;i<100;i++)
{
document.getElementById("firstDiv").innerHTML += "<div id = "firstDiv"><center><p id ="paragraph">Hello, World </p></center></div>";
}
}
printHundredtimes();
<div id="firstDiv">
<center>
<p id="paragraph">Hello, World</p>
</center>
</div>
your code should be something like this
for (i = 0; i < 100; i++){
var div = document.createElement('p');
div.textContent = "Hello World";
div.setAttribute('class', 'paragraph');
document.getElementById("paragraph-container").appendChild(div);
}
Id should be unique for all elements, otherwise you should use "class" if you want to identify more than one element.
<div id="paragraph-container" style="text-align: center;">
<p class="paragraph">Hello World</p>
</div>
As Jon P said in the comment, center tag is obsolete. You can put text-align to the parent element of the paragraphs through inline css or internal css
The reason it's not printing anything is because of an error:
"<div id = "firstDiv"><center><p id ="paragraph">Hello, World </p></center></div>";
You're quotes are not escaped.
Consider changing it to:
"<div id = \"firstDiv\"><center><p id=\"paragraph\">Hello, World </p></center></div>";
Even better, consider multiplying the string then adding it to the array. as follows:
function repeat(count, str) {
return str.repeat
? str.repeat(count)
: (function () {var arr = []; for (var i = 0; i < count; ++i) {arr.push(str);} return arr.join('');})()
}
function printHundredtimes() {
var str = repeat(100, '<center><p id ="paragraph">Hello, World </p></center>'));
document.getElementById("firstDiv").innerHTML = str;
}
Note, I detected you were writing another id "firstDiv" inside the existing "firstDiv", which didn't seem to make sense to have two of them.
The above method does not tax the dom with repeated changes. So its better only to write to the dom once. Instead as above, you can multiply the string 100 times and then write it to the dom. Otherwise the browser would start to get really slow and freeze up eventually because of all the constant changes to it.
Also its better practice to break down your big functions into smaller ones. It makes them easier to reuse elsewhere. Let a functions name describe its single action. That's pure programming.
So I am creating a table through javascript,
Part of my assignment says: "the output div should only contain the table of the most recent call"
It is a class where we don't talk too much syntax and I am new to web development and javascript.
I have this function and it works:
<body>
<div id="output"></div>
<script type="text/javascript">
var functionCreate = function(strInput) {
var dividedArray = strInput.split("\n");
var dLength = dividedArray.length;
var myRow, myCell;
var myNewTable = document.createElement('table');
myNewTable.border = "1"
for(var i = 0; i< dLength; i++){
if(dividedArray[i].length >0){
myRow = myNewTable.insertRow(-1);//here
for(var j = 0; j<dividedArray[i].length;j++){
if(dividedArray[i][j] != ','){
myCell = myRow.insertCell(-1); //here
myCell.innerHTML = dividedArray[i][j]
}
}
}
}
document.getElementById("output").appendChild(myNewTable);
};
</script>
</body>
When its called one time, it does what it is supposed to do. When it is called twice, I get two tables, naturally(?)
However I have no idea how to only use the table from last call . I have no access to where it is being called. Can anyone direct me towards the right direction? What is the most basic and straight forward approach that I should take to implement this?
The reason why your code is adding new tables is due to the line of code here:
document.getElementById("output").appendChild(myNewTable);
The function appendChild appends (adds) a child (myNewTable) to the end of the element of id output.
So when u run the function multiple times, it just keeps adding a newly created myNewTable element to the output div.
To make sure it only appends the latest table, clear the output div with something like document.getElementById('output').innerHTML = ""; at the beginning of your function
I just started learning JavaScript.
I'm trying to change the text on a click.What's wrong with this code.
Please let me know.
Thanks
<!DOCTYPE html>
<html>
<body>
<script>
function change_text(id)
{
var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");
var x = Document.getElementById("heading");
for(var i=0;i<arr.length;i++)
x.innerHTML=arr[i];
x.style.visibility="hidden";
}
</script>
<h1 onclick="change_text()" id="heading">Click on this text!</h1>
</body>
</html>
For one thing, you have two quotes here:
""oops! Once more!"
should be:
"oops! Once more!"
Document needs to be all lower-case (document).
change_text(id) is never used, and
x.style.visibility="hidden" needs to be moved outside the for loop.
You don't need a for loop at all, though, you just need to increment i++ every time the method is called, otherwise it will skip straight to "Goodbye".
<script>
var i = 0;
function change_text()
{
var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");
var x = document.getElementById("heading");
i++;
x.innerHTML=arr[i];
if(i >= arr.length) {
x.style.visibility="hidden";
}
}
</script>
EDIT:
EDIT2: OK, you got the idea before!
instead of "heading"
var x = Document.getElementById("heading");
you need to put the passed in value, id.
var x = Document.getElementById(id);
before this, you never actually use that id.
Also remember to pass that id in,
h1 onclick="change_text('heading')"
Change this line;
var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");
and this line
var x = Document.getElementById("heading");
to this;
var arr = new Array('Now Click Again','oops! Once more!','I\'m Leaving!','Good Bye!');
var x = document.getElementById(id);
First, i don't know if it is a typo in your question but you have one extra " in your string array, this is how it should look.
var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");
And I don't know what you are trying to do with your for loop but the text you are showing will always be the last one in your array. Could you clarify what your are trying to achieve with the text in the h1 element?
Last of all, if you hide your element clearly your text won't show up, you should remove this line unless there is something I didn't understand correctly :
x.style.visibility="hidden";
Oh, and I think that your script element should have a type="text/javascript"
<script type="text/javascript">...
Unrelated to the question but if you can't spot the strings mistake in your array maybe you should change IDE. Even Notepad++ colors the strings, it might have helped you figure this one out.
I have been strugling with this for a while and I am sure there is a simple answer to this. What happens is I remove a div called "payment" then dynamicaly create it again so I can add to it. That then gets repeated as the infomation that needs to be added to it changes.
I have mangaged to get this so far.
function clearPage()
{
var d = document.getElementById("contain");
var d_nested = document.getElementById("payment");
var deleteNode = d.removeChild(d_nested);
}
function createPayment()
{
payment = document.createElement("div");
payment.id = "mine";
document.getElementById("contain").appendChild(payment);
}
function printOnPage()
{
var x = names.length;
for( var i = 0 ; i < x ; i++ )
{
var para = document.createElement("p");
var paymentDiv = document.getElementById("payment");
paymentDiv.appendChild(para);
var txtName = document.createTextNode("Item: ");
para.appendChild(txtName);
var txtNameArray = document.createTextNode(names[i]);
para.appendChild(txtNameArray);
var txtQty = document.createTextNode(" Qty: ");
para.appendChild(txtQty);
var txtQtyArray = document.createTextNode(qty[i]);
para.appendChild(txtQtyArray);
var txtCost = document.createTextNode(" Cost: ");
para.appendChild(txtCost);
var txtCostArray = document.createTextNode(prices[i]);
para.appendChild(txtCostArray);
}
}
Related HTML
<div id="contain">
<p>Payment</p>
<div id="payment">
<br />
</div>
</div>
It needs the ID of payment for both my CSS rules and for my creating the text that goes in it.
This is the error I get in FireFox
Error: paymentDiv is null Source File:
http://itsuite.it.brighton.ac.uk/ks339/sem2/javascript/js.js Line: 76
Hope someone can provide some insight in to this and please tell me if I am completly off!
Thanks
Edit: Is it easior to clear the div rather than delete it, how would I go about doing such a thing?
In create_payment(), you set the ID to 'mine'. Shouldn't it be 'payment'?
I do not understand your requirements very well, but anyway you cannot create multiple items in the page using the same id attribute, if you want to duplicate an item and still have control over it, you should be using class instead.
Try switching your code into jquery it will be cleaner and easier to understand for you & me.
Your problem is the fact that in createPayment() you're setting the id to 'mine':
payment.id = "mine";
while later on in printOnPage() you're looking for the element using id 'payment':
var paymentDiv = document.getElementById("payment");
As you mention in your edit, it is far easier just to clear the div than to remove it, specially if you still need it later.
To clear a DIV-block just set it's content to empty:
document.getElementById('payment').innerHTML = "";
I hope you find a solution! Good luck!
I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/