can't select id or class in html dom - javascript

I'm new to HTML and especially HTML5.
I'm trying to select the header with id of mr and change it to the length of the number of items that have para as its class.
Nothing seems to be changing in my browser view.
Not sure why. Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerText = items.length;
</script>
<title>Title</title>
<html lang="en"/>
</head>
<body>
<header>
<h1 id="mr">This is a header</h1>
</header>
<nav>
Index
</nav>
<section>
<h1>Section 1</h1>
<article>
<p class="para">here is bla lakjfbsjkafb asje bfjlsaeb jlfkaseb ljkfabejkf bajekbf</p>
</article>
<article>
<p class="para"> <mark>here is some more shit</mark></p>
</article>
</section>
<footer>
</footer>
</body>
</html>

Neither para nor mr is present in DOM when the script is running.
Option 1
Just put the script part before closing body tag
<script>
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerText = items.length;
</script>
</body>
Option 2
If you still want to put it inside head tag put the js inside window.onload
<script>
window.onload=function(){
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerText = items.length;
}
</script>
Plunker

The thing you have to remember about HTML is that it's read and parsed from top to bottom. Meaning things that are on the top get rendered first while things at the bottom, later. It's usually good practice to put JS at the end of the body or defer it till the page loads.
<body>
<h1 id="mr">This is a header</h1>
<p class="para">here is bla lakjfbsjkafb asje bfjlsaeb jlfkaseb ljkfabejkf bajekbf</p>
<p class="para">
<mark>here is some more stuff</mark>
</p>
<script>
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerText = items.length;
</script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
function startup() {
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerText = items.length;
}
</script>
<title>Title</title>
<html lang="en"/>
</head>
<body onload="startup();">
<header>
<h1 id="mr">This is a header</h1>
</header>
<nav>
Index
</nav>
<section>
<h1>Section 1</h1>
<article>
<p class="para">here is bla lakjfbsjkafb asje bfjlsaeb jlfkaseb ljkfabejkf bajekbf</p>
</article>
<article>
<p class="para"> <mark>here is some more shit</mark></p>
</article>
</section>
<footer>
</footer>
</body>
</html>
the script runs before the page has loaded, to fix this we run the code once the body loads.

Put your js code in the scripts tag inside document.onload event, since after this event will ensure that by the time this event is fired your DOM elements are loaded and ready to be accessed by DOM API.
<script>
document.onload = function(){
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerText = items.length;
};
</script>

First your script should be at the end which help loading the content the user sees first faster and also it makes shure that all the DOM elements are loaded. Second i would replace log.innerText with log.innerHTML because somehow log.innerText doesnt really work for me and i prefer log.innerHTML anyway because there you can use html tags and stuff.
So heres a script that works at least for me:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<html lang="en" />
</head>
<body>
<header>
<h1 id="mr">This is a header</h1>
</header>
<nav>
Index
</nav>
<section>
<h1>Section 1</h1>
<article>
<p class="para">here is bla lakjfbsjkafb asje bfjlsaeb jlfkaseb ljkfabejkf bajekbf</p>
</article>
<article>
<p class="para">
<mark>here is some more stuff</mark>
</p>
</article>
</section>
<footer>
</footer>
<script>
var items = document.getElementsByClassName("para");
var log = document.getElementById("mr");
log.innerHTML = items.length;
</script>
</body>
</html>

Related

Change loaded content in an HTML file with javascript

Some content, in this case a navbar (navbar.php), is loaded into the index.html by Javascript. Now I want to change a navbar list item from "Home" to "Something else" using Javascript. But it seems that the script can not see the loaded content. The console gives an „document.getElementById(...) is null“ error. Following the code:
index.html
<!DOCTYPE html>
<html lang="de">
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("#navbar").load("navbar.php");
return false;
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<header>
<div id="navbar">
</div>
</header>
<main>
</main>
<footer>
</footer>
<script>
let myChange = document.getElementById("change").innerHTML;
myChange = "<a href='somethingelse.html'>Something else</a>";
</script>
</body>
</div>
</div>
</html>
navbar.php
<div>
<ul>
<li id="change">Home</li>
<li >Logout</li>
</ul>
</div>
Any idea what is wrong in the code?
Thanks a lot in advance.
You would need to use the load's callback function for load to know when the content has been added to the document.
$("#navbar").load("navbar.php", function() {
const myChange = document.getElementById("change");
myChange.innerHTML = "<a href='somethingelse.html'>Something else</a>";
});

Adding input to div

So I'm trying to create my own To Do list just to learn javascript and I'm stuck.
I've managed to add a new div with the input that the user writes, but there's no design.
<div class="isDo"> // HTML code
<p id="newTask">Task 1</p>
<hr>
</div>
function addTask() { // JavaScript Code
var div = document.createElement("div");
var taskAdd = document.getElementById("taskAdd").value;
div.innerHTML = taskAdd;
document.getElementsByClassName("isDo")[0].appendChild(div);
}
When I used append paragraph instead of div it the design works, but I want to ad an <hr> tag for each input value.
What way can I add an entire div with paragraph and hr tag?
This should do the trick :)
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="isDo">
<p id="newTask">Task 1</p>
<hr>
</div>
<button id="btn" >add a tag</button>
<script>
function addTask() { // JavaScript Code
var div = document.createElement("div");
var taskAdd = document.getElementById("newTask").innerHTML;
//change the id of the el because taskAdd doesn't point to an element
div.innerHTML = `<p>${taskAdd}</p><hr>`;
//this is the part where you add the text in taskAdd and the hr tag
document.getElementsByClassName("isDo")[0].appendChild(div);
}
var btn = document.getElementById("btn")
.addEventListener("click", addTask);
</script>
</body>
</html>
`
Try this below :
<!DOCTYPE html>
<html>
<title>Test Code</title>
<head>
<script>
function addTask() {
var div = document.createElement("div");
var taskAdd = document.getElementById("taskAdd").value;
div.innerHTML = taskAdd + "<hr>";
document.getElementsByClassName("isDo")[0].appendChild(div);
}
</script>
</head>
<body>
<input id="taskAdd">
<button onclick="addTask()">Add</button>
<div class="isDo">
<p id="newTask">Task 1</p>
<hr>
</div>
</body>
</html>

How do I direct a link to a page loaded into an iframe on another page and scroll it to location with a single click?

-- library.htm --
<iframe id="libcont" name="libcontent">
-- content.htm --
lorem ipsum <p name="scroll">lorem ipsum</p>
-- map.htm --
Read More...
Goal: clicking on the link within "map.htm" leads to "library.htm"
with "content.htm" already loaded into "libcont" iframe and scrolled
to the paragraph tagged "scroll". I can't find a HTML/CSS solution to this problem.
You can achieve this using javascript:
The anchor leads to library.htm, the onload function of library loads the iframe and uses scrollIntoView()(doc) to scroll to the right place.
map.htm
<!DOCTYPE html>
<html>
<body>
<h2>Map</h2>
Read More...
</body>
</html>
library.htm
<!DOCTYPE html>
<html>
<head>
<script>
loadContent = function() {
var frame = document.getElementsByName('libcontent')[0];
frame.onload = function() {
frames['libcontent'].document.getElementsByName('scroll')[0].scrollIntoView();
}
frame.src='content.htm';
};
</script>
</head>
<body onload="loadContent()">
<div style="height:1000px; background:gray;"> </div>
<h2>Library</h2>
<iframe id="libcontent" name="libcontent"></iframe>
<div style="height:1000px; background:gray;"> </div>
</body>
</html>
content.htm
<!DOCTYPE html>
<html>
<body>
<div style="height:1000px; background:black;"> </div>
<h2> Content </h2>
lorem ipsum <p name="scroll">lorem ipsum</p>
<div style="height:1000px; background:black;"> </div>
</body>
</html>
UPDATE: load different contents
To achieve this we are going to use a query parameter('content').
map.htm
<!DOCTYPE html>
<html>
<body>
<h2>Map</h2>
Content 1
Content 2
</body>
</html>
library.htm
<!DOCTYPE html>
<html>
<head>
<script>
loadContent = function() {
const urlParams = new URLSearchParams(window.location.search);
const content = urlParams.get('content');
// Check if the query param 'content' exists
if (content) {
var frame = document.getElementsByName('libcontent')[0];
frame.onload = function() {
frames['libcontent'].document.getElementsByName('scroll')[0].scrollIntoView();
}
// Loads the content
frame.src= content + '.htm#scroll';
}
};
</script>
</head>
<body onload="loadContent()">
<div style="height:1000px; background:gray;"> </div>
<h2>Library</h2>
<iframe id="libcontent" name="libcontent"></iframe>
<div style="height:1000px; background:gray;"> </div>
</body>
</html>
content2.htm
<!DOCTYPE html>
<html>
<body>
<div style="height:1000px; background:black;"> </div>
<h2> Content 2 </h2>
lorem ipsum <p name="scroll">lorem ipsum</p>
<div style="height:1000px; background:black;"> </div>
</body>
</html>
content1.htm
<!DOCTYPE html>
<html>
<body>
<div style="height:1000px; background:black;"> </div>
<h2> Content 1 </h2>
lorem ipsum <p name="scroll">lorem ipsum</p>
<div style="height:1000px; background:black;"> </div>
</body>
</html>
First of all, in content.htm use id instead of name for anchor:
<p id="scroll">lorem ipsum</p>
In map.htm use:
<a href='library.htm#scroll'>read more</a>
In library.htm use javascript to transfer the hash to the iframe URL:
<script>
document.getElementById('libcont').src = 'content.htm'+window.location.hash;
</script>
As result, the iframe will load as content.htm#scroll and scroll to the anchor.

POP up triggered by a click

I am trying to open a popup by clicking on a button.
Please check my below code and tell me why it isn't working.
I am using getreponse popup
http://www.reussirlegmat.com/2499-2/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button id="button" >Show it</button>
<script type="text/javascript" src="https://app.getresponse.com/view_webform_v2.js?u=BaAuE&webforms_id=7152504">{
"name": "myuniqueform2"
}
</script>
<script>
var myform = GRWF2.get('myuniqueform2'),
element = document.getElementById('button');
element.addEventListener("click", function(){
myform.show();
});
</script>
</body>
</html>
On your website, something has put <p>...</p> tags around every line of your script.
<p><script type="text/javascript" src="https://app.getresponse.com/view_webform_v2.js?u=BaAuE&webforms_id=7152504">{</p>
<p>"name": "myuniqueform2" </p>
<p>} </p>
<p></script> </p>
<p><script> </p>
<p>var myform = GRWF2.get('myuniqueform2'),</p>
<p>element = document.getElementById('button');</p>
<p>element.addEventListener("click", function(){ </p>
<p>myform.show(); </p>
<p>}); </p>
<p></script> </p>
<p></body></p>
<p></html></p>
Those are causing parse errors. Get rid of them.
I have no idea how you did this -- I suspect you edited the code with a word processor and then told it to export to HTML.

How to get an array from html using javascript?

I have an HTML like this:
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
How to use javascript to get an array like [Python, C++, PHP]?
I tried and wrote like this:
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
But the Output is 0, it's strange.
Your code logs 3: http://jsfiddle.net/t0ho10hw/
To get an array of languages you can convert the HTMLCollection to an actual Array, then .map it to get languages:
var myList = document.getElementsByTagName('h1');
var languages = [].slice.call( myList ).map( function( item ){
return item.innerHTML;
});
http://jsfiddle.net/t0ho10hw/1/
Or the "classic" way from before Array.map:
var languages = [];
for( var i=0; i<myList.length; i++){
languages.push( myList[i].innerHTML );
}
http://jsfiddle.net/t0ho10hw/2/
Using JQuery you could use this code :
var tab = [];
$(".item h1").each(function() {
tab.push($(this).text());
});
see Get an array of list element contents in jQuery
You need to be careful where and when you do your JS computation
<!DOCTYPE html>
<html>
<head>
<script>
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
</script>
</head>
<body>
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
</style>
</body>
</html>
Will give you 0, because the Javascript is called before any parsing of the HTML body by your browser.
You need either :
- to wait the page load
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
}
</script>
</head>
<body>
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
</style>
</body>
</html>
or write this javascript at the end of the page :
<!DOCTYPE html>
<html>
<head>
<script>
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
</script>
</head>
<body>
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
</style>
</body>
</html>
Even better is to write it at the end of the page with the window.onload. It will be shorter to reach the HTML part of your page and rendering would be faster (this is significant for large amount of JS, but in this case, you should do file inclusion)

Categories

Resources