I am trying to teach myself how to modify the DOM using JavaScript. I am at a loss about the following.
This is an HTML snippet.
<html>
<body>
<h1>A heading</h1>
<div id="myDIV"></div>
<script type="text/javascript" src="thejs.js"></script>
<script type="text/javascript">
document.getElementById("myDIV").innerHTML="<p>Try this one comes from script inside html source</p>"
</script>
</body>
</html>
I expect to get a similar result from the external js file linked in the script, which contains this:
document.getElementById("myDIV").innerHTML="<p>While this one comes from a separate JS file</p>";
But nothing happens... I realise this is probably silly, I apologize.
The first script runs and sets the content of the div to "While this one comes from a separate…"
Then, after some time which is imperceptible to a human, passes the second script runs and sets the content of the div to "Try this one comes from script…".
If you want both paragraphs to appear you need to append (e.g. with +=) the data instead of replacing it.
That said, appending chunks of HTML with innerHTML += can cause some issues (it's inefficient as that whole chuck of DOM has to be regenerated and it will blow away inline event handlers) so you are usually better off using the insertAdjacentHTML method instead.
The output depends on where you have included the external js. If you have included it before your embedded script, it will not have any effect, as eventually, it will be overridden by your embedded script. However, if you include the external js after your embedded js, it will work as you want to.
<html>
<body>
<h1>A heading</h1>
<div id="myDIV"></div>
<script type="text/javascript" src="thejs.js"></script>
<script type="text/javascript">
document.getElementById("myDIV").innerHTML="<p>Try this one comes from script inside html source</p>"
</script>
<script type="text/javascript" src="external.js"></script>
</body>
</html>
Related
I have two embedded scripts in my HTML files but only the first one runs. The second one doesn't execute, it's just supposed to change the text of the paragraph. I'm really not familiar with javascript and don't know if there's some async wizardry going on. If I remove the jquery include (and change the code to use the plain method of changing elements), it works fine.
<html>
<body>
<p id="next-track">
Next Track
</p>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"/>
<script>
$("#next-track").html("Bye JavaScript!");
</script>
</html>
You have to separate the script tag, you cannot close it on the opening.
<html>
<body>
<p id="next-track">
Next Track
</p>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
$("#next-track").html("Bye JavaScript!");
</script>
</html>
Javascript external file code:
document.getElementById("not-working").innerHTML=person.firstname+person.nickname+person.lastname+"is"+"awesome.";
I am trying to write the innerHTML in my HTML document by writing the above in my external Java Script file but it's not working.
My HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="home.js"></script>
<p id="demo">
Hello, this is Maqnoon.
<button onclick="myFunction()">Click me</button>
</p>
<p id="hello"></p>
<p id="not-working"></p>
</body>
</html>
Put your external JS importing <script> tag right after the ending </body> tag. Also, put your JS codes inside of the DOMContentLoaded listener like this,
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
function myFunction() {
// ...
}
});
Edit:
Explanation: The browser interprets the HTML from top to bottom, line by line. When you put the JS in the header section of the HTML, there is a possibility that your JS will finish running before the browser reaches to the elements in the later sections of your HTML. In that case, the JS will not be able to see the elements that are going to be loaded right after, maybe a few milliseconds or nanoseconds later. This is why it is advisable to put the <script> tags after your </body> element so that by the time the browser reaches to the JS, the HTML elements are already loaded.
To take it a step further, there is the 'DOMContentLoaded' event which is fired by the browser when it finishes loading the HTML. So, we put our JS code in it to make sure that the code runs after the entire HTML is loaded and available.
I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help.
Basically, I need to load an HTML snippet into a page. This works fine when the snippet contains just HTML, but not when it contains a script.
I've stripped down my code to the bare minimum for clarity. This is index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
$('#banner').load('banner.html');
});
</script>
</body>
</html>
And banner.html contains just the following (as an example):
<h2>Subheading</h2>
<script>
document.write('Hello');
</script>
The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (i.e. it just displays "Hello" and nothing else).
Any help greatly appreciated!
document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello".
Just remove the document write :
<h2>Subheading</h2>
<p id="test"></p>
<script>
document.getElementById('test').innerHTML = 'hello';
</script>
that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html)
one way to understand this is by replacing certain content of banner.html rather than the whole document.
banner.html
<h2>Subheading</h2>
<div id="divID"></div>
<script>
$('#divID').html('hello'); //using jquery .. gets the element with id as divID and replace the HTML
</script>
here i am replacing just the div whose id is "divID" rather than replacing the enrite document
is it possible to get javascript to output html where the javascript code is?
For example
<html>
<head>
<title>
</title>
</head>
<body>
<div>header</div>
<div>main
<script type="text/javascript" language="javascript">
// print some html here, maybe google
</script>
</div>
<div>footer</div>
</body>
</html>
Where the end results would look like:
<html>
<head>
<title>
</title>
</head>
<body>
<div>header</div>
<div>maingoogle</div>
</script>
</div>
<div>footer</div>
</body>
</html>
I understand that I can give the containing div and id and then get javascript to insert the anchor take like that, but I just wanted to know if it's possible to do this directly, as in write the html exactly where the javascript is?
Use document.write('YOUR_TEXT') for that
<script type="text/javascript" language="javascript">
document.write('google')
</script>
jsFiddle demo
Yes, although there are a lot of nuances to document.write, it'll output its contents immediately after the calling script element.
warning: document.write will obliterate your DOM once the dom is closed for writing. If you need to call a function asynchronously, you'll have to do DOM manipulation, otherwise document.write will rewrite everything with whatever it's supposed to output. This leads to unintentional results, which is why it's often discouraged.
How do I add text/elements to a target element (div) using getElementById (without jquery) when the page loads?
Here's my markup currently:
<html>
<head>
<title>test</title>
<script language="javascript">
/document.getElementById('content').innerHTML = 'Fred Flinstone';
</script>
</head>
<body>
<div id="content">
dssdfs
</div>
</body>
</html>
<script type="text/javascript">
function dothis()
{
document.getElementByID('content').innerHTML = 'Fred Flinstone';
}
</script>
<body onLoad="dothis()">
...
</body>
I think what is happening is that your script is executing before your document is ready. Try placing your javascript in a body load event.
The quickest (although not the best) way to do it is to put your script block towards the end of the HTML file (after the <div> you wish to modify).
The better way to do it is to register for DOM load notification
If you want it to execute after the page loads, then you need to observe the DOM loaded event. You can do that by subscribing to the DOM load event in the script block and then put the code that manipulates the DIV in the event handler.
The tricky part is that different browsers may need slightly different ways to register to be notified when the DOM is loaded (that's were jQuery or a different library becomes useful)
Here's some more information about different ways to register for a callback to be called when the DOM is loaded. The information may be a bit out of date as more modern versions of the popular browsers have become more standards compliant now: http://www.javascriptkit.com/dhtmltutors/domready.shtml