Toggle text with JavaScript - javascript

I am learning JavaScript.
I am trying toggle the text on a page using the replaceChild() method. I came up with the code below. I don't understand why it will not work. Pls help.
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
if (b4[0].innerHTML=="Before"){
be.replaceChild(l8,b4[0])
}
if (b4[0].innerHTML=="After") {
be.replaceChild(l88,b4[0]);
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>

As CBrone wrote, you have to create h1 instance first, store it to variable and then call innerHML on the variable.
Another problem is if structure. First you replace the element and then test the same element for another condition and do another operation. In this case is better to use if ... else if ... statement instead of if ... if ..., which is the root of your problem.
Here is working toggleText function
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
l88.innerHTML="Before";
if (b4[0].innerHTML == "Before")
{
be.replaceChild(l8, b4[0]);
}
else if (b4[0].innerHTML=="After")
{
be.replaceChild(l88, b4[0]);
}
}
Here is working fiddle

In addition to what’s been said in comments already:
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
After this your variables do not contain references to the created elements, but the string values that you assigned to their innterHTML. (The result of an assignment operation is the assigned value.) And trying to pass text values instead of element references to replaceChild afterwards must fail for that reason.
Do this in two steps – create the elements first and save their reference into the variables – and then manipulate their innerHTML afterwards.
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
var l88 = .innerHTML="Before";
(And maybe use better suited variable names, because if you keep your current “naming scene” up you’ll get confused sooner or later.)

May I suggest the following, for better readability:
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1")[0];
if (b4.innerHTML=="Before") {
b4.innerHTML = "After";
}
else if (b4.innerHTML=="After") {
b4.innerHTML = "Before";
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>

Related

TypeError: getElementById is null

<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"
Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).
It should be document.getElementById('submit').onclick(clicked());
your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');
You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>

How to grab text from URL and place in JS array?

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.
Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

Replacing function contents dynamically in JavaScript

How do you completely replace a function in JavaScript?
I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).
If you want to replace that function, just use
somefunction = function() {
alert(New code!); // syntax error, btw
};
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
It seems you are trying to work with strings, not the function itself. Just do this instead:
someFunction = function () { /* your function code here */ }

Inserting javascript global variable in <div> tag in HTML body

I have the following tag in HTML:
<div data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
I have the values 6204 and 2 in a couple of global variables in the script section:
<html>
<head>
<script>
...
var newNeId = gup('neId');
var newNeGroupId = gup('neGroupId');
...
</script>
</head>
</html>
Is it possible to have these variables in the div tag in the HTML body? If so, how?
To clarify this a bit more, I need to have the URL in the tag something like this:
url: 'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/'+newNeGroupId+'/'+newNeId
I changed it according to your requirement:
<html>
<head>
<script type="text/javascript">
// example data
var newNeId = 10;
var newNeGroupId = 500;
window.onload = function(e){
var myDiv = document.getElementById("myDiv");
myDiv.setAttribute("data-dojo-props", "url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/" + newNeId + "/" + newNeGroupId + "', label:'text'");
}
</script>
</head>
<body>
<div id="myDiv" data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
</body>
</html>​
You could add them to the <div> using the same datalist pattern (MDN docu) as Dojo:
<div id="savebox" data-newNeId="6204" data-newNeGroupId="2"></div>
These attributes are then accessible by the element.dataset.itemName.
var div = document.querySelector( '#savebox' );
// access
console.log( div.dataset.newNeId );
console.log( div.dataset.newNeGroupId );
As #EricFortis pointed out, the question remains, why you want to do this. This only makes sense, if you pass those values on from the server side.
Take one parent div then set its id and then you can rewrite whole div tag with attributes using innerHTML.
document.getElementById('id of parent div').innerHTml="<div data-dojo-type=/"dojox.data.XmlStore/"
data-dojo-props=/"url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'/"
data-dojo-id=/"bookStore3/"></div>";
you can append values you wants in innerhtml now.
here's simple native js code to do it
var body = document.getElementsByTagName('body')[0];
var myDiv = document.createElement('div');
myDiv.setAttribute('id', 'myDiv');
var text = 'newNeId: ' + newNeId +
'<br/> newNeGroupId: ' + newNeGroupId';
body.appendChild(myDiv);
document.getElementById('myDiv').innerHTML = text;

Accessing inline CSS properties using getElementsByClassName

I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?
You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");
You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);
If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")
I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];
Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example
If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/

Categories

Resources