I am trying to modify the body section based on the tagName, using JavaScript. But my webpage is loading infinitely when I use insertBefore() method to insert a tag before the <h1> tag. This problem is not happening when I try to insert before some other elements. I am new to JS, please help me.
This is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Para 1</p>
<p>Para 2</p>
<h1 id="head1">Para 3</h1>
<p id="parax"></p>
<div id="div1">
<p>Hello</p>
</div>
<ul id="mylist1">
<li>Script</li>
<li>deep learning</li>
<li>software testing</li>
<li>Python programming</li>
<li>Database systems</li>
</ul>
<p id="firstp">I was supposed to be first.</p>
<input type="button" onclick="myFunc()">
</body>
<script type="text/javascript">
var cn=document.body.children;
for(var i=0;i<cn.length;i++){
if(cn[i].tagName=="DIV"){
var h1 = document.createElement("H1");
var text = document.createTextNode("h1 tag inserted");
h1.appendChild(text);
cn[i].appendChild(h1);
}
else if(cn[i].tagName=="UL"){
var lis= cn[i].childNodes;
for(var j=0;j<lis.length;j++){
if(lis[j].innerHTML=="Python programming")
lis[j].innerHTML="machine learning";
}
}
else if(cn[i].tagName=="H1"){
var p=document.createElement("P");
var text=document.createTextNode("New para inserted before");
p.appendChild(text);
document.body.insertBefore(p,cn[i]);
}
else
document.write();
}
</script>
</html>
At this line i am facing problem (I think so) :
document.body.insertBefore(p,cn[i]);
Because you with this line code:
document.body.insertBefore(p,cn[i]);
increase number of document.body.children and every time you insert child you and number of body children and you never not hit last index.
please add this to see:
document.body.insertBefore(p,cn[i]);
alert(document.body.children.length); // add this line after insertBefore
see every alert show the number of document.body.children was increase
Thanks to Mr #foad , I got the answer for my question. Actually the insertBefore() method is inside a for loop. So in every iteration, a new tag is added to the body and the length of the body increases by 1. This caused the infinite loading.
The correction is to add a break statement after the insertBefore method:
document.body.insertBefore(p,cn[i]);
break;
This terminates the loop after adding the <p> tag before <h1> tag.
Related
i have some project that need to change multiple iframe with some array
example
<ul>
<li>
<iframe src="test.html">
<head></head>
<body>
<div class="content">
<p>test</p>
</div>
</body>
</iframe>
</li>
<li>
<iframe src="test.html">
<head></head>
<body>
<div class="content">
<p>test</p>
</div>
</body>
</iframe>
</li>
</ul>
I need to change <div class="content"><p>test</p></div> for each iframe with an array ["<h1>tittle</h1>","<h1>tittle2</h1>"].
For the first iframe it will be replaced with the HTML in array[0] and second iframe with array[1].
Can anyone help? Thanks
Try with replaceWith()
var array = ["<h1>tittle</h1>", "<h1>tittle2</h1>"]
$(document).ready(function() {
$('iframe').load(function() {
$('iframe').each(function(a) {
$(this).contents().find('body').children('.content').replaceWith(array[a]);
})
})
})
Here you go :
var arr = ["<h1>tittle</h1>","<h1>tittle2</h1>"];
var found=0;
$('iframe').each(function(){
if($(this).find('.content p').length > 0){
$(this).find('.content p').parent().replaceWith(arr[found]);
found++;
}
});
It searches for every iframe, then checks if it contains the tags you want, then replaces them with your array's replacement.
The variable 'found' allows you to travel through the array.
As much as you tagged your post with "jQuery", I suppose you can use this library.
So you just need to iterate over the .each() function.
var array = ["<h1>tittle</h1>","<h1>tittle2</h1>"];
$(".content").each(function(i) {
$(this).html(array[i]);
});
You can obviously replace html() with replaceWith() if you really want to delete the div.
You could try this:
var iframe = $('iframe');
for (i=0; i<iframe.length; i++){
var current = $('iframe')[i+1].contentWindow.document.body.innerHTML;
$('iframe')[i].contents().find('html').html(current);
}
A JS newbie question:
I would like to inactivate a part of a html code (which I manually would do by <!-- ... -->) by Javascript, depending on a numeric variable (which I extract from the file name): If var > 10 do inactivate the code.
EDITED:
If possible only simple Javascript!
A demo html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script>
var param = 10;
</script>
</head>
<body>
<p>Paragraph One</p>
<p>Beginning of the part to be removed if param > 10</p>
E-Mail<br><br>
This is simply something other.
Etc.
Etc.
<p>End of the part to be removed</p>
<p>Paragraph Ten</p>
</body>
</html>
Put everything you want to remove/hide inside one div with a specific class or id, then add an if condition and hide or remove the required div once the condition is true.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<p>Paragraph One</p>
<div id="to_remove">
<p>Beginning of the part to be removed</p>
E-Mail<br><br>
This is simply something other.
Etc.
Etc.
<p>End of the part to be removed</p>
</div>
<p>Paragraph Ten</p>
<script type="text/javascript">
var param = 11;
if(param >10) document.getElementById("to_remove").remove();
//OR if you want to show the div later use this:
//if(param>10) document.getElementById("to_remove").style.display = 'none';
</script>
</body>
</html>
You can remove the elements from the DOM, e.g. by using removeChild():
document.getElementById('div').removeChild(document.getElementById('p2'));
<div id="div">
<p id="p1">Paragraph one</p>
<p id="p2">Paragraph two</p>
</div>
You can use css property for the same, add two classes active and inactive with css .active{display:block} and .inactive{display:none}.now you can use jquery to add and remove active and inactive classes according to your condition.like in jquery you can write
if(var > 10){
$("div").addClass('inactive');
}else{
$("div").removeClass('inactive');
}
A CSS + jQuery way of achieving this could be by adding the class disabled:
if(condition) {
var element = document.getElementByID('#sample_ID');
element.addClass("disabled");
}
This is assuming that you contain the code to be disabled in the <div id="sample_ID">
If you just want to hide it, you can do this by using CSS.
E.g. to hide <div id="myDiv">Bla</div> you'd use this:
var element = document.getElementById("myDiv");
element.style.display = "none";
And if you want to show it again at some point:
element.style.display = "block";
Live example:
function hideDiv() {
var element = document.getElementById("myDiv");
element.style.display = "none";
}
function showDiv() {
var element = document.getElementById("myDiv");
element.style.display = "block";
}
#myDiv {
border: solid 1px green
}
<button onclick="hideDiv()">Hide</button>
<button onclick="showDiv()">Show</button>
<br/>
<div id="myDiv">Bla</div>
For some reason, any event listener functions won't work on my browser(chrome), but they work on code pen? I been at this for about 2 hours, any thoughts?
Code pen link: http://codepen.io/koushkilla/pen/JXLVBX
<header>
<script src="pleasegodhelpme.js"></script>
<h1>Javascript Events</h1>
</header>
<main>
<h4>Add Numbers:</h4>
<p>
<input id="num-one"> + <input id="num-two">
</p>
<p id="add-sum"></p>
</main>
JS- FIle:
var numOne = document.getElementById("num-one");
var numTwo = document.getElementById("num-two");
var addSum = document.getElementById("add-sum");
numOne.addEventListener("input", add);
numTwo.addEventListener("input", add);
function add() {
var one = parseFloat(numOne.value) || 0;
var two = parseFloat(numTwo.value) || 0;
addSum.innerHTML = "your sum is: " + (one+two);
}
What happens is that your Javascript code is executed before the DOM has loaded. This means that you're making calls in the Javascript code to elements that don't exist yet.
The easiest way to solve this problem is to place your <script> tag just before the closing <body> tag. It's always good practice to place Javascript at the end of your page since it also increases loading times.
<body>
<header>
<h1>Javascript Events</h1>
</header>
<main>
<h4>Add Numbers:</h4>
<p>
<input id="num-one"> + <input id="num-two">
</p>
<p id="add-sum"></p>
</main>
<script src="pleasegodhelpme.js"></script>
</body>
EDIT: Here's the JSFiddle for the following question.
http://jsfiddle.net/x28ojg6w/
So I'm trying to activate a template with JavaScript and it wasn't working for a while, and I finally fixed it by changing a For-In loop into a For loop in a seemingly unrelated block of code.
The following code is the For-In loop I changed to a for loop. The commented out code was the original code that didn't work and the uncommented for loop is the now working code. This code was used to change font size for text within all instances of a class element:
var release4 = document.getElementsByClassName("release-4");
// for (item in release4){
// release4[item].style.fontSize = "2em";
// };
for (var i = 0 ; i < release4.length ; i++) {
release4[i].style.fontSize = "2em";
}
This is the code I used to activate my template. It is not part of the release-4 class:
var tmpl = document.getElementById('hidden');
document.body.appendChild(tmpl.content.cloneNode(true));
And here is the HTML that goes with it:
<html>
<head>
<title>Manipulate the DOM</title>
</head>
<body>
<div id="release-0">
<p class="release-4"> Here is some text, add a class "done" to the parent div</p>
</div>
<div id="release-1">
<p>remove the #release-1 div</p>
</div>
<h1>Change this text to finish release 2</h1>
<div id="release-3">
<p class="release-4"> add CSS to this div</p>
</div>
<template id="hidden">
<div>
<h1> Congrats! You finished the challenge.</h1>
<img src="http://media.giphy.com/media/2UpzC3iPenf44/giphy.gif">
</div>
</template>
<script type="text/javascript" src="home_page.js"></script>
</body>
</html>
My question is why did changing the For loop make a difference? Thanks everyone!
All other code in the JS file only affect IDs release-0, release-1, and release-3, and the h1 tag. The class name, display, innerHTML, and background color were the only changes made to them.
If I console.log() item in the for in loop it yields:
0
1
length
item
namedItem
I think length, ìtem and namedItem make it error.
Updated:
With Array.from it works as expected.
var release4 = Array.from(document.getElementsByClassName("release-4"));
for (item in release4){
release4[item].style.fontSize = "2em";
};
I'm just getting started in programming and somehow can't come up with any sensible approach to the following problem, so any help would be greatly appreciated! I have a .html file structured like this:
<head>
<title>ABC</title>
</head>
<body>
<div class="norm">
...
<span class="jnenbez">13</span>
....
<div class="Absatz">text</div>
<div class="Absatz">text</div>
<div class="Absatz">CITE HERE**</div>
The "norm" div is the one parent node. The "jnenbez" span and the "Absatz" divs are inside the "norm" div, but how deeply they are nested can vary. Now I want to cite the "CITE HERE" area, meaning to generate the output of "jnenbez 13 Absatz 3 ABC" - meaning getting the text content of the "jnenbez" span of the same "norm" div, getting the index number of the "Absatz" div, since it is the third child "Absatz" of the "norm" div and getting the content.
1) How could I give this string to the user, so he could copy paste it somewhere else? It seems it is not easily possible to modify the copy+paste behavior of Firefox. An obvious solution would be to put the output in brackets like [jnenbez...] at the end of each divs text content, but that would reduce readability of the html...
2) Is it even possible to automatically generate this output via JQuery?
Not sure about a good way to store/display the info.
Also, unsure of what other mark-up you would have in the class='norm' container. This is vitally important and impacts entirely the shape of the useful solution.
I've assumed a particular structure - one that says the first contained span is one of interest. Another assumption is that the only divs in the container are of interest and need to be counted.
I'm sure you can break it easily enough. :D
<!DOCTYPE html>
<html>
<head>
<script>
function onBtnPress(element)
{
var result;
var cont = element.parentNode;
var span = cont.getElementsByTagName('span')[0];
result = span.className + " ";
result += span.innerHTML + " ";
var divList = cont.getElementsByTagName('div');
result += divList[0].className + " ";
result += divList.length+" ";
result += document.title;
cont.getElementsByTagName('p')[0].innerHTML = result;
}
</script>
<title>ABC</title>
</head>
<body>
<div class="norm">
<span class="jnenbez">13</span>
<div class="Absatz">text</div>
<div class="Absatz">text</div>
<div class="Absatz">CITE HERE**</div>
<button onclick='onBtnPress(this);'>click me</button>
<p>[string here]</p>
</div>
<div class="norm">
<span class="Crapple">8</span>
<div class="ipod">worst</div>
<div class="ipod">music</div>
<div class="ipod">player</div>
<div class="ipod">I ever</div>
<div class="ipod">bought</div>
<div class="ipod">CITE HERE**</div>
<button onclick='onBtnPress(this);'>click me</button>
<p>[string here]</p>
</div>
</body>
</html>