How to get div content in javascript variable? - javascript

I am trying to get the content of a div in a JavaScript variable.
I did try some code:
<html>
<head>
<script>
function data(){
alert();
var MyDiv1 = document.getElementById('newdata')
alert(MyDiv1);
}
</script>
</head>
<body>
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1 <!-- The content I'm trying to get -->
</div>
Logout
</body>
</html>
But it does not work correctly.

Instead of
var MyDiv1 = document.getElementById('newdata')
alert(MyDiv1)
it should be
var MyDiv1 = document.getElementById('newdata').innerHTML
alert(MyDiv1)
OR
var MyDiv1 = document.getElementById('newdata')
alert(MyDiv1.innerHTML)
With .innerHTML you will get the html of specified element in the DOM.
EDIT:-
SEE DEMO HERE

You must use innerHTML.
<html>
<head>
</head>
<body>
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
</body>
<script>
function data() {
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1);
}
</script>
</html>

Related

javascript document.ready is replacing the whole content issue

i am trying to create this <div id="myid" >Hello Wordl!</div> in the body of the page but my code problem is , after waiting 10 seconds it will replace this <div id="myid" >Hello Wordl!</div> with whole content of my page so it will only show this div.
here's my javascript code
<script>
setTimeout(function(){
$("body").prepend("<div id='myid'>hello world</div>");
},10000);
},10000);
</script>
and my page is like this
<html>
<head>
<style type="text/css">
body {margin:0;padding:0;}
</style>
<title></title>
</head>
<body>
<script>
setTimeout(function(){
$("body").prepend("<div id='myid'>hello world</div>");
},10000);
</script>
<!-- New div created by javascript must be here -->
<div id="1">Keep This Div</div>
</body>
</html>
Working Code
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<style type="text/css">
body {margin:0;padding:0;}
</style>
<title></title>
</head>
<body>
<script>
setTimeout(function(){
$("body").prepend("<div id='myid'>hello world</div>");
},10000);
</script>
<!-- New div created by javascript must be here -->
<div id="1">Keep This Div</div>
</body>
</html>
If you want to add an element to your html body you can just create it and then append it like this:
var elemDiv = document.createElement('div');
document.body.appendChild(elemDiv);
You can then add attributes and also innerHTML via Javascript like this:
elemDiv.id = 'myid';
elemDiv.innerHTML = 'Hello World!'
Nothing is overwritten in your code. You try to create element (in wrong way) and do nothing with it.
<div id="id1">Keep This Div</div>
<script>
setTimeout(function() {
var el = document.createElement('div');
el.id = 'myid';
el.innerHTML = 'Hello World!';
document.getElementById('id1').prepend(el);
}, 2000);
</script>
Note that id="1" is invalid value, I've changed it to id1 in my example.

How To Add Prefix in Class's Name Using JavaScript

Hi All I am new in JavaScript. I have one HTML file. And I need to add some word in the class's name. Is there any way to do it using JavaScript?
For Example
<!Doctype HTML>
<html>
<head>
<style>
.heading{color:red;}
.text{color:red;}
</style>
</head>
<body>
<h1 class="heading">This is heading.</h1>
<p class="text">This is my text.</p>
</body>
</html>
In need to add "test-" in the class name in head and body both using JavaScript.
After using JavaScript function it should look like this.
<!Doctype HTML>
<html>
<head>
<style>
.test-heading{color:red;}
.test-text{color:red;}
</style>
</head>
<body>
<h1 class="test-heading">This is heading.</h1>
<p class="test-text">This is my text.</p>
</body>
</html>
It would be great help! Thanks in advance.
//$(".heading").addClass('test-heading').removeClass('heading');
//$(".text").addClass('test-text').removeClass('text')
$('.text').attr('class', function() {
return $(this).attr('class').replace('text', 'test-text');
});
$('.heading').attr('class', function() {
return $(this).attr('class').replace('heading', 'test-heading');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<head>
<style>
.heading{color:red;}
.text{color:red;}
</style>
</head>
<body>
<h1 class="heading">This is heading.</h1>
<p class="text">This is my text.</p>
</body>
</html>
You can loop Inside the body and add new class.
$("body").children().each(function(index, element) {
var oldclass = $(this).attr('class');
var newClass = "test_" + oldclass
$(this).removeClass(oldclass).addClass(newClass);
});
.test_heading {
color: blue;
}
.test_text {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<style>
.heading {
color: red;
}
.text {
color: red;
}
</style>
</head>
<body>
<h1 class="heading">This is heading.</h1>
<p class="text">This is my text.</p>
</body>
</html>
Find all classes of any element, loop through it, add new class and remove existing classes
var element = "body";
var className= "test-";
var classes = $(element).attr('class').split(" ");
classes.forEach(function(i,obj){
$(element).addClass(className + i);
$(element).removeClass(i);
});

Call a javaScript url when a visitor clicks inside div

How to execute a javaScript url when a visitor clicks inside div
Like this example :
<html>
<head>
<meta charset="UTF-8">
<style>
.youtube .play,.youtube img{cursor:pointer;position:absolute}
.youtube{position:relative;padding-bottom:56.23%;height:0;overflow:hidden;max-width:100%;background:#000;margin:5px}
.youtube embed,.youtube iframe,.youtube object{position:absolute;top:0;left:0;width:100%;height:100%;z-index:100;background:0 0}
.youtube img{bottom:0;display:block;left:0;margin:auto;max-width:100%;width:100%;right:0;top:0;border:none;height:auto;-webkit-transition:.4s all;-moz-transition:.4s all;transition:.4s all}
.youtube img:hover{-webkit-filter:brightness(75%)}
.youtube .play{height:72px;width:72px;left:50%;top:50%;margin-left:-36px;margin-top:-36px;background:url(//i.imgur.com/TxzC70f.png) no-repeat}
</style>
</head>
<body>
<div class="youtube" data-id="YQHsXMglC9A"></div>
</body>
<script>
/* Light YouTube Embeds by #labnol */
/* Web: http://labnol.org/?p=27941 */
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = labnolThumb(v[n].dataset.id);
div.onclick = labnolIframe;
v[n].appendChild(div);
}
});
function labnolThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function labnolIframe() {
var iframe = document.createElement("script");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.dataset.id + "?autoplay=1");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
</script>
</html>
Like this picture
image
.
Html code + javascript :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="a" style="background-color:#999; height:90px; width:250px;" >Click here</div>
</body>
</html>
Javascript :
<script type="text/javascript">
document.write("Hello World!");
</script>
Or :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
How do I run javaScript url when a visitor clicks inside div ?
Something liked this would do it...
function clickMe() {
alert("You clicked me!")
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="a" style="background-color:#999; height:90px; width:250px;" onclick="clickMe()" >Click here</a></div>
</body>
</html>
First of all, instead of trying to run a script, you should try to run a function.
For example
function test(){
document.write("Hello World!")
}
function test2(){
document.getElementById("output").innerHTML = "Hello World!"
}
<div onclick="test()">
<p> Click me </p>
</div>
<div onclick="test2()">
<p> Click me (won't remove screen) </p>
</div>
<div id="output">
</div>
Clicking on the first div will call the test() function. This function will however overwrite everything on the screen, that's not what you want.
The second method doesn't do that, instead it sets the content of the third div to "Hello World!"
I believe you want to run a JavaScript function when your div gets clicked. You just need to add an onclick() event to your <div> tag and declare that function. So your div would be something like this:
<div id="a" style="background-color:#999; height:90px; width:250px;" onclick="writeFunction();">Click here</div>
And the function, with the same name as you declared on your onclick:
<script type="text/javascript">
function writeFunction(){
document.write("Hello World!");
}
</script>
As you have used document.write and i have kept that, it does not show the result that you have illustrated in your picture and your div is vanishing. In order to do as you have imagined, you have to add a <p> element which is initally blank:
<p id='text'></p>
and then ask your function to set its text, like this:
document.getElementById('text').innerHTML = "Hello World!";
You can learn more here: https://www.w3schools.com/jsref/event_onclick.asp

Hide body until it finishes loading

I created this code so my page would be hidden until it finishes loading. But my code doesn't work as I expected. I expected this to hide the BODY until the OnLoad event was triggered.
However, instead, it just stays hidden.
Any help would be appreciated, if there is maybe another, better method of hiding the BODY until it finishes loading, or what's wrong with this one.
Here's what I've tried so far:
function unveil() {
var thebod = document.getElementById("testbody");
thebod.STYLE = "display: block;"
}
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>
</HTML>
The DOMContentLoaded event of the window object can do this. But, don't hide the body, hide a wrapper instead. And, when you set the style, make sure to set the style of a CSS property, not the style object itself.
window.addEventListener("DOMContentLoaded", function(){
document.getElementById("wrapper").style.display = "block";
});
#wrapper { text-align:center; background:#e0e0e0; display:none;}
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY>
<div id="wrapper">
HELLO WORLD!
<!-- The following is only added to create a delay in the
parsing of the document -->
<script>
for(var i = 0; i < 100000000; ++i){ var x = i / 3.14; }
</script>
</div>
</BODY>
</HTML>
You're not setting the elements 'style' correctly:
You can either do:
element.style.display = "block";
Or
element.setAttribute('style', "display: block");
Here is a working example:
function unveil() {
var thebod = document.getElementById("testbody");
thebod.style.display = "block";
}
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>
</HTML>
Your issue is here:
thebod.STYLE = "display: block;"
which should read:
thebod.style.display = 'block';
Here is the complete approach (using unobtrusive javascript):
var body = document.getElementsByTagName('body')[0];
function unveil() {
body.style.display = 'block';
}
window.addEventListener('load', unveil, false);
body {
display: none;
}
div {
text-align: center;
}
<div>HELLO WORLD!</div>
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY ID="testbody" onload="testbody.style.display = '';" style="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>
</HTML>

Closing an iFrame via Javascript

I'm working on an application with modal overlays that appear within iFrames when the corresponding buttons are pressed. To close one of these modal overlays, the Cancel button is defined in the parent window this way:
Cancel
I'd like to replace this with a JavaScript function (let's call it onCancel() ) so I can reset some values if needed in addition to closing the overlay. What is the JavaScript equivalent to "#close"?
You can't close an iFrame, you either have to remove or hide it. The example below removes the iframe. If you just want to hide you can replace the last line (containing removeChild with this one frame.style.display="none"; You can then get it back by using this line frame.style.display="block";
<!DOCTYPE html>
<head>
<title>test</title>
<style type="text/css">
.top {
height: 100px;
width: 200px;
background-color: blue;
}
</style>
<script type="text/javascript">
function removeIFrame() {
var frame = document.getElementById("iframe");
frame.parentNode.removeChild(frame);
}
</script>
</head>
<body>
<div class="top" onclick="removeIFrame();"></div>
<iframe id="iframe" src="/" width="200" height="100"></iframe>
<div class="top"></div>
</body>
<!DOCTYPE html>
<head>
<title>test</title>
<style type="text/css">
.top {
height:100px;
width:200px;
background-color:green;
}
</style>
<script type="text/javascript">
function removeIFrame() {
var frame = document.getElementById("target");
frame.parentNode.removeChild(frame);
}
</script>
</head>
<body>
<div class="top" onclick="removeIFrame();"></div>
<iframe id="target" src="http://www.disney.com" width="100" height="100"></iframe>
<div class="top"></div>
</body>
The approach that works for me is to define the following JavaScript function in the parent page:
function onCancel()
{
var myIFrame = document.getElementById("myIFrame");
var myForm = myIFrame.contentDocument.myForm;
var stuffWasChanged = myIFrame.contentDocument.stuffWasChanged;
if (stuffWasChanged == "true")
myForm.action = "reset.do";
myForm.submit();
location.href = '#';
}
Note that if the stuffWasChanged flag was not set to true, then no action is defined for the form in question, so the modal overlay simply goes away without any servlet method being called.

Categories

Resources