How to display a string javascript in HTML - javascript

In my HTML file I have a div with id="list".
Now I want to display a string from my javascript in my html. page. but nothning
happen. In my html file, i've imported the srcipt file. Here's how it looks in my script file:
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;

Whenever you're targeting DOM elements (i.e you want to use document.getElementById("my-element") or similar) you need to first check if the document has loaded.
You can do this in either of the following ways:
window.onload = function(){
//Now that the window has loaded we can target DOM elements here
}
OR
document.addEventListener('DOMContentLoaded', function () {
//Now that the contents of the DOM have loaded we can target DOM elements here
});
So a full example (putting your script code in an external file i.e list.js) would look like this:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8">
<title>My list website</title>
<script src="list.js"></script>
</head>
<body>
<div id="list"></div>
</body>
</html>
list.js
window.onload = function(){
//We use window.onload to check the window has loaded so we can target DOM elements
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
}

place your code in this and it will work
window.onload = function() {}

You need to put the JavaScript code after your dom and also wrapped with Script tag.
Example: This will work since we rendered the HTML first and then executed the js into it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This Will WorK</title>
</head>
<body>
<div id="list" ></div>
<script>
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
</script>
</body>
</html>
But this will NOT work since the JavaScript is being executed before dom rendered. Also this will probably throw an error Cannot set property 'innerHTML' of null" because getElementById will not be able to find the associated dom.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This Will Not WorK</title>
</head>
<body>
<script>
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
</script>
<div id="list" ></div>
</body>
</html>

Here is a succinct way to do it with template strings. Just wrap everything in a function you assign to window.onload:
<script>
window.onload = () => {
const namesArray = ['lars', 'bo', 'ib', 'peter', 'jan', 'frederik'];
const list = `<ul>${namesArray.map(name => `<li>${name}</li>`).join('')}</ul>`;
document.getElementById('list').innerHTML = list;
};
</script>
<div id="list"></div>

Related

Cannot read property 'id' of null - JS error

I have the following html code:
<!DOCTYPE html>
<html>
<head>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
</body>
</html>
Yet in the console, I'm receiving an error when it reaches line 9 when it says "type of null does not exist", but clearly the id of the div must exist because I had it declared as an id in the body. How is this possible?
Your html elements aren't loaded when the script is loaded and so don't exist at the time the javascript is executed. Changing the order of your code will solve the problem:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</body>
</html>
Your JS code is probably running before your HTML has fully rendered. To avoid this, don't run your code until the 'DOMContentLoaded' event has fired.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// your code here
});
</script>
Please load javascript after the whole html body won't get any error

Frameset innerHTML changes

I am trying to achieve something like, www.example.com/en/test/page.html will load the frameset of www.example.com/2.html.
Which I am able to do.
But now once 2.html is loaded in frameset I want to replace .html" to .html" target="_top".
So that all the links present in 2.html would be opened in the parent window instead of frameset itself.
<!DOCTYPE html">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script>
(function divert()
{
var urlString = parent.document.URL;
var a1 = new RegExp("/en/test/page");
if(a1.test(urlString)) {document.write('<frameset cols="100%" rows="100%"><frame src="http://www.example.com/2.html"></frameset>');}
else{document.write('<frameset cols="100%" rows="100%"><frame src="http://www.example.com/3.html"></frameset>');}
var str = document.getElementById("demo").innerHTML;
var res = str.replace('.html"', '.html" target="_top"');
document.getElementById("demo").innerHTML = res;
})();
</script>
</head>
<body onLoad="divert()"></body>
Hi #Vinod you can use target="_parent"if you have only 2 level of frame-set or just want to open the link to the parent frame only..
Or to open the link to the current page you can use target="_top"
You can read more about it here
UPDATE:
You can also use JavaScript to detect if page is loaded inside a frame and than add target to the links pragmatically..
You can use window.location.origin and parent.window.location.origin to detect if you are in the frame
And than you can use following code to add target using JavaScript
using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
without using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
<!DOCTYPE html">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script>
(function divert()
{
var urlString = parent.document.URL;
var a1 = new RegExp("/en/test/page");
function targetUrl(){
var links = document.getElementById("demo").contentDocument.documentElement.getElementsByTagName('a');
for(var i =0; i<links.length; i++){
links[i].target = '_parent';}
}
if(a1.test(urlString)){document.write('<frameset cols="100%" rows="100%"><frame id="demo" src="http://www.example.com/2.html"></frameset>');}
else{document.write('<frameset cols="100%" rows="100%"><frame id="demo" src="http://www.example.com/3.html"></frameset>');}
document.getElementById("demo").onload= targetUrl;
})();
</script>
</head>
<body></body>
</html>

Safari Extension Popover access innerHTML

I'm currently developing a Safari Extension, which should search newspaper articles for country or location names. For that, I'd like to search the innerHTML of the current website on which I am. My extension consists of a button in my task bar, which toggles a popover that should show a list of the countries/locations mentioned in an article and a map on which those places are marked.
The problem is that I have no clue how to access the innerHTML in search.js.
I'd like to search the innerHTML for specific strings, e.g. "Germany". The apple documentation is not really clear on how to access the website content from an extension. Or how to access anything once one got an safari.application.activeBrowserWindow object.
Safari Extensions Development Guide
Thanks a lot for your help in advance!
This is my code so far:
popover.html
<!DOCTYPE html>
<html>
<head lang="en">
<link href="popover.css" rel="stylesheet">
<title>popover</title>
</head>
<script src="nameSearch.js"></script>
<body>
<div id="locationList">
<ul id="resultList"></ul>
</div>
<div id="map"></div>
</body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="map.js"></script>
</html>
globalPage.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Global Page</title>
<script type="text/javascript">
var countriesDE = ['Odessa'];
var results = ['Germany'];
</script>
</head>
<body>
</body>
</html>
nameSearch.js
const myGlobal = safari.extension.globalPage.contentWindow;
myGlobal.results.push(safari.application.activeBrowserWindow.page.innerHTML);
if (document.documentElement.lang.indexOf("de") != -1) {
for (i = 0; i < myGlobal.countriesDE.length; i++) {
if (safari.application.activeBrowserWindow.innerHTML.indexOf(myGlobal.countriesDE[i]) != -1) {
myGlobal.results.push(myGlobal.countriesDE[i]);
}
}
}
map.js
const myGlobal = safari.extension.globalPage.contentWindow;
var ul = document.getElementById("resultList");
for (i = 0; i < myGlobal.results.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(myGlobal.results[i]));
li.setAttribute("id", myGlobal.results[i]);
ul.appendChild(li);
}
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200] // This is only a test
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('map'));
chart.draw(data, options);
}
You need to inject a script into a web page if you want to access its DOM.

Javascript/HTML Image Change

My task for my Javascript class is to create a script for this page that changes the image every 3 seconds. I think my code is correct, however Firebug tells me "document.getElementByID is not a function." Can someone show me what I am doing incorrectly?
This is my JS script.
<script type="text/javascript">
var i = 0
var lightArray = ["pumpkinOff.gif", "pumpkinOn.gif"]
var currentLight = document.getElementByID('light')
// ChangeLight Method Prototype
function changeLight() {
currentLight.src = lightArray[i++];
if (i == lightArray.length) {
i = 0;
}
}
setInterval(changeLight, 3000)
</script>
Here is my edited HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript for Programmers</title>
</head>
<body>
<h2>Happy Halloween!</h2>
<img id="pumpkin" src="pumpkinoff.gif" alt="pumpkin">
<script src="../Script/spooky.js"></script>
</body>
</html>
Incorrect capitalisation on
var currentLight = document.getElementByID('light')
Should be:
var currentLight = document.getElementById('pumpkin')
I have attached a working fiddle:
http://jsfiddle.net/11csf4k2/
It's a typo it should be:
var currentLight = document.getElementById('light'); //Not ID
It should be Id not ID:
document.getElementById('light');
Also note that you don't have element with id light on your page. It probably should be
document.getElementById('pumpkin');

Appending HTML to parent from inside iFrame without jQuery

I'm developing in an application where new code is introduced via iframes only. I'm trying to create a function (running inside an iFrame) that will append some html after the iFrame in which it is running. I'd rather not introduce jQuery to resolve this issue. Here is a sample
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
newDivInParent.innerHTML = 'Hello World! I am outside the iFrame';
iFrame.appendChild(newDivInParent);
}
I don't receive any exceptions, but I never see any results either.
Update with full code
Call this page InnerPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
iFrame.appendChild(newDivInParent);
parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
}
</script>
</head>
<body>
<button onclick="AppendDivAfteriFrame()">Append HTML</button>
</body>
</html>
Call this page OuterPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<iframe src="InnerPage.html" id="MyiFrame"></iframe>
</body>
</html>
This works:
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
iFrame.parentNode.appendChild(newDivInParent); //Edited here
parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
}

Categories