How to select every element in an element list - javascript

I'm a beginner programmer and I am trying to select every element in a class array to style them. I have tried using the generic selector * but this has not worked and I have not found a suitable solution. eg.
var link = document.getElementsByClassName;
link[*].style.color = "#eee";

From https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName
[document.getElementsByClassName] returns an array-like object of all child elements which have all of the given class names.
You need to specify what class to select, and then you'd have to iterate over each element in the returned array.
Suppose you have this HTML:
<p class="foo">Hello</p>
<p class="foo">World</p>
Then you'd need something like this in JavaScript:
var foo_items = document.getElementsByClassName("foo");
for(var i = 0; i < foo_items.length; i++) {
foo_items[i].style.color = "#eee";
}
Of course, if you're using jQuery, this could be simplified to
$(".foo").css("color", "#eee")

Try using jquery loop or javascript loop. In jquery use $.each loop to parse through the loop elements and apply style to each element. I have added a sample code here using javascript and jQuery.
jQuery implementation.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
</head>
<body>
<p class="itemclass">Element 1.</p>
<p class="itemclass">Element 2.</p>
<p class="itemclass">Element 3.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var items = document.getElementsByClassName("itemclass");
$.each(items, function(index, item){
item.style.backgroundColor = "red";
});
}
</script>
</body>
</html>
Javascript Implementation
<!DOCTYPE html>
<html>
<body>
<p class="itemclass">Element 1.</p>
<p class="itemclass">Element 2.</p>
<p class="itemclass">Element 3.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var items = document.getElementsByClassName("itemclass");
var loopVar = 0;
var loopLength = items.length;
for(loopVar = 0; loopVar < loopLength; loopVar++){
items[loopVar].style.backgroundColor = "red";
}
}
</script>
</body>
</html>

Try this in your browser console.
function getAllLinks() {
return document.getElementsByTagName('a')
}
var links = getAllLinks()
function colorElements(elements, value) {
for(var i = 0; i < elements.length; i++) {
elements[i].style.color = 'red';
}
}
colorElements(links, 'red')
Code above should fetch all the links on the page and color them red.
Now with better ES6+
// this code requires links from the code above
var allLinks = Array.from(links)
allLinks.forEach(link => link.style.color = 'green')
Code above should take all the links on the page and color them green.
Advice: Do not touch browser or users anchor colors for accessibility reasons.

Related

dynamically add EventListener doesn't work as expected

When I try to dynamically fill a wrapper element with HTML elements, and then add an EventListener for that element, it only uses the last value.
window.onload=function(){
sW="";
for(var i = 0; i < 5; i++) {
var e = document.createElement('div');
e.innerHTML = "test div number "+i;
e.addEventListener('click', function() {alert("t:"+i);});
document.getElementById('wrap').appendChild(e);
}
}
<html>
<body>
<div id="wrap"></div>
</body>
</html>
That's because var keeps the the reference to the variable. Use let instead.

Hide Multiple Elements in html using javascript

I'd like to show/hide multiple ID of elements.
I have a problem with the javascript in my HTML file.
Here's the javascript:
<Script type="text/javascript" language="JavaScript"><!--
function HideContent(d){
document.getElementById(d).style.display = "none";
}
function ShowContent(d){
document.getElementById(d).style.display = "block";
}
//--></script>
And my HTML:
<div class = "left" id="colsxmenu">
<ul>
<li> ENGLISH
<li>FRENCH
Actually, if I select ENGLISH it works good hiding the colsxmenu, but what I need is if I select FRENCH it should hide more than only 1 elements.
I tried to add ('colsxmenu';'colsxmenu2'), but that didn't works.
You can pass an array of elements to your function
<div id="first">first</div>
<div id="second">second</div>
ENGLISH
<script>
function HideContent(obj) {
for (var i = 0; i < obj.length; i++) {
document.getElementById([obj[i]]).style.display = 'none';
}
}
</script>
Define your HideContent function to accept variable number of argument. It should be some thing like below to hide multiple elements.
<script>
function HideContent() {
if (arguments.length > 0){
for(var i=0; i < arguments.length; i++{
document.getElementById(arguments[i]).style.display = "none";
}
}
}
</script>
After that you can call it like
HideContent('colsxmenu');
HideContent('colsxmenu', 'uniqename');

Can't get correct dynamically added divs count

I have a body element, and in this body element I have a child element with id fullpage. And this element contains child element with classname section. In function load_works() I add two more section elements
<body>
<div id="fullpage">
<div class="section">
<!-- Content -->
</div>
</div>
<script src="js/main.js" charset="utf-8"></script>
<script type="text/javascript">
load_works();
</script>
</body>
Contents of main.js:
function load_works() {
var container = document.getElementById('fullpage');
for (var i = 0; i < 2; i++) {
var new_section = document.createElement('div');
new_section.className = "section";
container.appendChild(new_section);
}
}
The problem is, that when I try to count section elements with getElementsByClassName() like this after load_works() is executed
function some_function() {
var sections = document.getElementsByClassName('section');
console.log(sections.length);
}
it always returns 1, and this, I think, is because I have only one static section element. querySelectorAll() of course and other get- fucntions also aren't working. So, how can I achieve the correct result with pure Javascript, not jQuery?
You better should place all javascript inside one file like main.js and then you only need to call some_function() after load_works().
function load_works() {
var container = document.getElementById('fullpage');
for (var i = 0; i < 2; i++) {
var new_section = document.createElement('div');
new_section.className = "section";
container.appendChild(new_section);
}
}
function some_function() {
var sections = document.getElementsByClassName('section');
alert(sections.length);
}
load_works();
some_function();
<div id="fullpage">
<div class="section">
<!-- Content -->
</div>
</div>

getElementsByClassName doesn't work

I try to hide some HTML elements onload and then show and manipulate them. The code works fine when I use element's individual IDs with getElementById() method. But when I try to do it more efficiently using the classes, it doesn't work. Here is the code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body onload="HideModals()">
<p id="p1" class="MyModal99">1. I will disappear or not.</p>
<p id="p2" class="MyModal99">2. I will disappear or not.</p>
<button id="toggle">Toggle</button>
<button id="hide">Hide</button>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#p1").toggle();
});
$("#hide").click(function(){
$("#p2").hide();
});
});
</script>
<script>
function HideModals() {
//document.getElementById("p1").style.display = 'none';
//document.getElementById("p2").style.display = 'none';
document.getElementsByClassName("MyModal99").style.display = 'none';
}
</script>
</body>
</html>
You cannot apply properties in bulk like that. This is why using jQuery is preferred for things like this:
$('.MyModal99').css('display', 'none');
If you want to do this without jQuery:
var nodes = document.getElementsByClassName("MyModal99");
for(var i = 0; i < nodes.length; i++) {
nodes[i].style.display = 'none';
}
It's because getElementsByClassName() returns an array-like object of elements. You need to access a specific element in order to change the style object.
You could iterate over the elements:
var elements = document.getElementsByClassName("MyModal99");
Array.prototype.forEach.call(elements, function (el) {
el.style.display = 'none';
});
or:
var elements = document.getElementsByClassName("MyModal99");
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
document.getElementsByClassName returns an array, which doesn't have a "style" property. You need to iterate over the array:
function HideModals() {
//document.getElementById("p1").style.display = 'none';
//document.getElementById("p2").style.display = 'none';
var modals = document.getElementsByClassName("MyModal99");
for (var i=0; i < modals.length; i++) {
modals[i].style.display = 'none';
}
}
The issue here is that document.getElementsByClassName("MyModal99") returns a list of items, so you'd have to loop through them and apply your properties one at a time. Something like this:
var elements = document.getElementsByClassName("MyModal99");
for ( var e in elements ) {
e.style.display = "none";
}
If you need to support older browsers, do it the old fashioned way without a for..in loop:
var elements = document.getElementsByClassName("MyModal99");
for ( var i = 0 ; i < elements.length ; ++i ) {
elements[i].style.display = "none";
}
Thats because document.getElementsByClassName returns an array of nodes. You need to iterate each of the returned nodes to set their styles individually.
var eleArray = document.getElementsByClassName('MyModal99');
for(var i = 0; i < eleArray.length; i++) {
eleArray[i].style.display = 'none';
}
You can use a for loop to cycle through all of the elements in the collection returned by getElementsByClassName like this:
var results = document.getElementsByClassName("MyModal99");
for (var i = 0; i < results.length; i++) {
results[i].style.display = 'none';
}
working demo: http://jsfiddle.net/gratiafide/3qg308bq/2/
I had difficulties with this code because I didn't know how to name jQuery functions. Now i know. Here is the corrected code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
</head>
<body onload="HideModals()">
<p id="p1" class="MyModal99">1. I will disappear or not.</p>
<p id="p2" class="MyModal99">2. I will disappear or not.</p>
<button id="toggle">Toggle</button>
<button id="hide">Hide</button>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#p1").toggle(100);
});
$("#hide").click(function(){
$("#p2").hide(100);
});
});
function HideModals() {
$('.MyModal99').css('display', 'none');
}
</script>

Get Attributes Value for multiple class

Im a Javascript beginner. I want to get attribute value on multiple class elements. I tried with IDs, but it's not revelent since IDs are supposed to be unique.
My HTML looks like this :
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_1">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_2">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_3">
Any help would be appreciated.
Thanks
First close your anchor Tags
Test1
Test2
Test3
then use this javascript function
function myJavascriptFunc(item)
{
alert(item.getAttribute("data"));
return false
}
and let me know if it works
Trying using this:
function test(){
var x = document.getElementsByClassName("myClass");
var i;
for (i = 0; i < x.length; i++) {
var val = x[i].innerHTML; //innerHTML returns the written text inside the element tag
alert(val);
alert(x[i].getAttribute("data")); //this will give you the data attribute
}
}
You can get any other attribute you like from that element just by replacing the innerHTML by that attribute's name
I'm too late as always, but I would use the HTML 5 dataset attribute:
<!DOCTYPE html>
<html>
<head>
<script>
function doSomething(classname,func,datakey)
{
var hrefs = document.getElementsByClassName(classname), // get all elements with the class
i = 0; // initialize the loop
for(;i < hrefs.length; i++) // iterate through all elements
{
func(hrefs[i].dataset[datakey]); // execute the passed function with the content of the dataset as first argument
}
}
function alertval(value) // example function to do something with it
{
alert(value);
}
window.onload = function ()
{
doSomething("Test",alertval,"something"); // just test it
}
</script>
</head>
<body>
Test1
Test2
Test3
</body>
</html>
You are probably wondering why you can't just reach the data attribute using the this keyword from myJavascriptFunc(). That's because you are using inline event registration, and the this keyword then refers to the window object. To get around this you must make sure the this keyword is actually written into the onclick property.
var elems = document.getElementsByClassName('test');
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = myJavascriptFunc;
}
function myJavascriptFunc() {
alert(this.getAttribute('data'));
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
FooBar_One<br>
FooBar_Two<br>
FooBar_Three
</body>
</html>
A way to see the difference:
<element onclick="myJavascriptFunc()">. // this refers to the window object as the element does not get passed along.
<element onclick="alert(this.getAttribute('data'));">. // this refers to the element.

Categories