How to get an array from html using javascript? - 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)

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>";
});

Constantly refreshing/receiving output <div>

So I have this div on my site
<div class="col-sm-4" >
<div id="RealTimeClose" class="nest">
<div class="title-alt">
<h6>
<span class="fontawesome-resize-horizontal"></span> Deposit Feed</h6>
<div class="titleClose">
<a class="gone" href="#RealTimeClose">
<span class="entypo-cancel"></span>
</a>
</div>
<div class="titleToggle">
<a class="nav-toggle-alt" href="#RealTime">
<span class="entypo-up-open"></span>
</a>
</div>
</div>
<div id="RealTime" style="min-height:296px;padding-top:20px;" class="body-nest">
<?php include('table1.php'); ?>
</div>
</div>
And Im trying to get it to continously load data from table1.php after like 1 second intervals... how can i go about doing this
$(function() {
function reloadTable(){
$.get( "table1.php", function( data ) {
$( "#RealTime" ).html( data );
});
}
reload = setInterval(reloadTable, 1000);
});
Uing JQuery / AJAX will solve your problem.
<html>
<head>
<title>New document</title>
<script src="jquery.js"></script> <!-- This is for including the JQuery, found at https://jquery.com -->
</head>
<body>
<script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
});
var Interval = setInterval(function(){
$("#users").load("table1.php"); // $("#users") is a selector to select the id "users", and the load function explains itself...
}, 1000/*Refresh rate : currently one second*/);
</script>
<p>Users found: </p>
<div id="users">Users found her</div>
</body>
</html>

can't select id or class in html dom

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>

jQuery toggle is not working

var resultsList = $("#test");
resultsList.text("Hello. This is jQuery!");
var tB = jQuery("#toggleButton");
tB.on("click", function() {
resultsList.toggle(400);
});
I believe the syntax is correct because the browser console is not reporting any error.
On loading the page, the toggle is not working as expected. Any idea, what am I missing here?
My HTML is :
<div id="results" class="bordered-image">
<button id="#toggleButton">Hide</button>
<div id="test">This is where results will live...eventually.</div>
</div>
Put the Jquery code into document.ready() like this: Check the Fiddle also.
$(document).ready(function(){
var resultsList = $("#test");
resultsList.text("Hello. This is jQuery!");
var tB = jQuery("#toggleButton");
tB.on("click", function() {
resultsList.toggle(400);
});
});
Your id attribute should be id="toggleButton" instead of id="#toggleButton"
HTML:
<div id="results" class="bordered-image">
<button id="toggleButton">Hide</button>
<div id="test">This is where results will live...eventually.</div>
</div>
id="toggleButton" instead of id="#toggleButton" will do.
Wrap it inside the document ready function.
see this example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="results" class="bordered-image">
<button id="toggleButton">Hide</button>
<div id="test">This is where results will live...eventually.</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var resultsList = $("#test");
resultsList.text("Hello. This is jQuery!");
$("#toggleButton").click(function() {
resultsList.toggle(400);
});
});
</script>
</html>
Thanks
Amit
<div id="results" class="bordered-image">
<button id="#toggleButton" onclick="myff();">Hide</button>
<div id="test">This is where results will live...eventually.</div>
</div>
<script>
function myff(){
$("#test").toggle();
}
</script>

Correct usage of .innerHTML

Trying to add content into individual div-containers I stumbled on the command .innerHTML, which I tried to implement accordingly. Strangely I get the following error:
*Uncaught TypeError: Cannot read property 'innerHTML' of null *
I'm running the code over my local Apache server if that makes any difference.
index.html
<html>
<head>
<title>Welcome</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="header">
<h1>Startseite</h1>
</div>
<div id="container">
<div id="left">
Navigation
</div>
<div id="content"></div>
<div id="right"></div>
<div class="clr"></div>
</div>
</body>
</html>
javascript.js
var navidiv = document.getElementById('left');
navidiv.innerHTML += "FirstElement";
Put it in window.onload
window.onload = function()
var navidiv = document.getElementById('left');
navidiv.innerHTML += "FirstElement";
}
The element has to be present in the DOM, before you can access it in JS
You have to ensure that your DOM elements have loaded before accessing them with javascript.
Since you are using jquery, your javascript can simply be
$(function() {
var $navidiv = $('#left');
$navidiv.html($navidiv.html() + 'FirstElement');
});
try this
html
<div id="header">
<h1>Startseite</h1>
</div>
<div id="container">
<div id="left">
Navigation
</div>
<div id="content"></div>
<div id="right"></div>
<div class="clr"></div>
</div>
javascript.js
$( document ).ready(function() {
var navdiv=$("#left").html();
$("#left").html(navdiv+"FirstElement");
});
see DEMO

Categories

Resources