How to alert all content of page on button click with JavaScript - javascript

I need to get all the content of page including all codes on JavaScript alert. Please check the code.
function getContent() {
var content = document.getElementsByTagName('html').value;
alert(content);
}
<html>
<head>
</head>
<body>
Some more code..........
Get Content
</body>
</html>
I am trying to execute the function from inside the page and trying to get the value. It is giving me undefined error

.getElementsByTagName() returns a NodeList collection of elements. You need to access the first index with [0]. In addition to this, it does not have a .value property. You're looking for .innerHTML instead.
Note that you also shouldn't make use of onclick, and instead should make use of unobtrusive JavaScript by adding an event listener.
This can be seen in the following:
function getContent() {
var content = document.getElementsByTagName('html')[0].innerHTML;
alert(content);
}
document.getElementsByTagName('a')[0].addEventListener('click', getContent);
<html>
<head></head>
<body>
Some more code..........
Get Content
</body>
</html>
Note: this will not work as expected in a Fiddle, but will work as expected on a proper website.

This can be achieved via the innerHTML field of a DOM element. Consider making the following changes to your getContent() function:
function getContent() {
var { innerHTML } = document.querySelector('html');
alert(innerHTML);
}
<html>
<head>
</head>
<body>
Some more code..........
<p> and some more content </p>
Get Content
</body>
</html>

Related

I'm trying to get the innerHTML of all <h2> tags and set that as their individual IDs but I'm not sure how to go about it

Basically I have a bunch of <h2> tags and without going into detail, I can't manually assign them IDs. So I THINK I could use .innerhtml to somehow get the <h2> text and assign that as IDs for them but I'm not sure how to get started.
Is this even possible?
The html would look something like this:
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
As the comments have said, you should avoid using innerHTML unless you are sure you want the HTML content of the element - Using innerText instead will make sure you only receive the plaintext
You can use querySelectorAll to get all of the h2 elements in an HTMLCollection
You can then simply loop over this and update the property directly by using:
ele.id = ele.innerText;
Or you can make use of setAttribute like this:
ele.setAttribute('id', ele.innerText);
.
You might also want to use .toLowerCase() after the innerHTML, just to have a more standard ID styling
document.querySelectorAll('h2').forEach((ele) => {
ele.id = ele.innerText;
});
console.log(document.getElementById('History').innerText);
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
You will want to use the DOM to find all the h2 elements and process accordingly:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
var h2s = document.querySelectorAll('h2');
h2s.forEach(function(h2Element) {
h2Element.id = h2Element.innerText;
});
</script>
</body>
</html>

Retrieving DOM elements in the outer HTML scope from an inner HTML scope

I was embedding html in a website (template based) and I wanted to manipulate the html outside of my user-defined html. The way it basically works on the site is:
<html>
<head></head>
<body>
<p>Hello World!</p>
</body>
<html>
<script>
document.getElementsByTagName("p").innerHTML = "Greetings World!";
</script>
</html>
</html>
However, this will only look for "p" elements within the inside html scope. My question is, is there a way to retrieve DOM elements from the inner html scope to the outer html scope? Here's the code I'm working with:
<!-- Website HTML -->
<html>
<textarea id="np-text">Hello World!</textarea>
<!-- Custom HTML -->
<html>
<body>
<button onclick="myFunction()">Change Value</button>
<script>
function myFunction() {
document.getElementById("np-text").innerHTML += '<span class="hover"><span></span></span>';
}
</script>
</body>
</html>
</html>
The main problem is that I cannot change the outer HTML scope in any way; the only html I can define is not in the same scope of what I want to change.
You can't "change the outer HTML scope in any way", because there is not supposed to be one. The HTML you have included in your question is completely wrong in every way imaginable and will make any HTML validator facepalm.
The only valid way to have an "inner HTML tree" inside an existent HTML document is through the use of an iframe or object. In the case of an iframe, in order to be able to access the content of the outer tree, both the content of the parent window and the one of the iframe are required to originate from the same domain.
If all of the above is in place, you can access the document of the parent window and subsequently the textarea using the following code:
parent.document.getElementByID("np-text");
In addition, you also have an error in your JavaScript code, where you use:
document.getElementsByTagName("p").innerHTML = "Greetings World!";
The getElementsByTagName method returns an HTMLCollection, instead of a single HTMLElement, which doesn't have the innerHTML method. In order to change the innerHTML of a collection of elements, you can use the following code:
/* Fetch all 'p' elements. */
var pCollection = document.getElementsByTagName("p");
/* Iterate over every element in the collection and change its content. */
[].forEach.call(pCollection, (element) => element.innerHTML = "Greetings World!");
// Your original code:
// document.getElementsByTagName("p").innerHTML = "Greetings World!";
// New code:
document.getElementsByTagName("p")[0].innerHTML = "Greetings World!";
<html>
<head></head>
<body>
<p>Hello World!</p>
</body>
</html>
I notice you use getElementsByTagName("p"), as a short notice you'll see the s after getElements, with this s it meant it'll be an HTMLCollection since you might have many p element in your HTML, [0] meant the first <p> element in this HTML page.
For a better code you should do something like this:
document.getElementById("greeting").innerHTML = "Greetings World!";
<html>
<head></head>
<body>
<p id="greeting">Hello World!</p>
</body>
</html>
<html>
You can use id="" function to have a safer code since you said it's in template which you might not sure of its position, while id in the HTML must be unique, it's proving that you'll find the element/place you want to change and also having a better code.

.getElementsByClassName()[] -- what am I not understanding?

I am working with HTML, CSS, jQuery, and JavaScript, all on one HTML page. Generally, I trying to figure out for the first time how to access information from the HTML body for use in my JavaScript code.
I want to set a variable in JavaScript equal to the string contained in the data attribute of one of my <div> elements.
Can I use document.getElementsByClassName()[] in my JavaScript to actually pull the information out of the HTML document? In examples on W3schools and elsewhere, I only see it used to change the value of some HTML element, not to actually use its input. Is there something more fundamental that I'm missing, here?
____here's my more specific code (where div.onlyOne is the only div of that class, and has the data-need attribute "string i need"):
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need")
Why will this not store "string i need" into myVar?
It works, make sure though, that you run the script after the markup or DOM load, or else the script will not find the element as it has not yet been loaded.
After in markup
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
<script type="text/javascript">
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
</script>
</body>
</html>
DOM load
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
});
</script>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
</body>
</html>
May I suggest you use document.querySelector('.onlyOne') instead in the future. With that you can narrow down the result list in a more efficient way.
Src: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
<div class="onlyOne" data-need="some text">...</div>
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
https://jsfiddle.net/howa6w1o/
since you are using jQuery, you can simplify your code to get the contents of the data-attribute: as follows:
$(document).ready(function(){
var myVar = $(".onlyOne").eq(0).data("need");
})

Javascript: Does not change the div innerHTML

I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

Categories