Can't change style : display using getelementbyclassname - javascript

document.getElementByClassName('xyz').style.display = 'none';
I am unable to hide class content.

document.getElementsByClassName return an array like object. you can use following script for this
document.getElementsByClassName('xyz')[0].style.display = 'none';
or if you want to hide all .xyz element
var x = document.getElementsByClassName("xyz");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = 'none';
}

function show(){
var element = document.getElementsByClassName('elem');
console.log(element);
element[0].style.display = 'block';
}
.elem {
display: none;
}
<div> visible
<div class="elem">hidden
</div>
<button type="button" onclick="show()">click</button>
</div>
getElementsByClassName returns an array, you can't directly set the style of element like it.

You need to do something like:
let elem = document.getElementsByClassName('xyz')[0];
elem.style.display = 'none';

document.getElementsByClassName elements is a live HTMLCollection of found elements.
<div class="xyz">
test content
</div>
<button type="button" onclick="document.getElementsByClassName('xyz')[0].style.display = 'none';">Hide Content </button>
<button type="button" onclick="document.getElementsByClassName('xyz')[0].style.display = '';">Show Content </button>

$("#afficher_commentaire").change(function(){
// alert("OK");
if($(this).prop("checked") == true){
var commentaire_date_fin_fourniture = document.getElementsByClassName("commentaire_date_fin_fourniture");
for (var i = 0; i < commentaire_date_fin_fourniture.length; i++) {
commentaire_date_fin_fourniture[i].style.display='block';
}
}
else if($(this).prop("checked") == false){
var commentaire_date_fin_fourniture = document.getElementsByClassName("commentaire_date_fin_fourniture");
for (var i = 0; i < commentaire_date_fin_fourniture.length; i++) {
commentaire_date_fin_fourniture[i].style.display='none';
}
}
});

Working version
hide = function(){
document.getElementsByClassName('xyz')[0].style.display="none";
}
<input class="xyz" type="text"/>
<button onclick="hide();">Click to hide!</button>

If you really want to do things this way, then of course first you need to spell getElementsByClassName correctly; you saw this error in the console, right? Then, you need to know that getElementsByClassName returns an array-like things; you saw that in the documentation, right? So you have to loop over it, or take the first element with [0], or whatever.
But in general, it's bad practice to retrieve elements from the DOM like this and set their styles directly. Instead, take advantage of CSS, which will do 90% of the work for you. Here, I'd use a single higher-level class which controls the behavior, and just set that:
<main id="main">
<div class="xyz"></div>
<main>
Then write your CSS as
main.hide-xyz .xyz { display: none; }
To hide the xyz element, then you need a single JS statement:
document.getElementById("main").classList.add("hide-xyz");
To remove it:
document.getElementById("main").classList.remove("hide-xyz");
Or toggle it:
document.getElementById("main").classList.toggle("hide-xyz");
Once you wrap your head around this style, you'll find yourself writing much less JavaScript that needs to all kinds of DOM lookups and loops and setting of styles.

document.getElementsByClassName always returns an array like object. Specify the array[0] number.
Typescript
let hiddenLocales = document.getElementsByClassName('localeMatch') as HTMLCollectionOf<HTMLElement>;
let hideParentNode = hiddenLocales[0]?.parentElement;
hideParentNode?.remove(); // Remove the element
hideParentNode?.style.display = "none"; // Hide the element

Related

addEventListener on class

I need to use getElementsByClassName because I have several same buttons etc.
I work on a wordpress loop that displays a button for each new article, and a registration form must appear on each event when we click on the button.
When I click on the button, I want the form to be displayed and the button to be hidden.
Someone can help me ?
Sorry if there are mistakes, I am French.
var bouton = document.getElementsByClassName('btn_inscription');
var formulaire = document.getElementsByClassName('formulaire');
var MyFonction = function{
formulaire.style.display = 'block';
bouton.style.display ='none';
}
for (var i = 0; i < bouton.length; i++) {
bouton[i].addEventListener('click', MyFonction);
}
getElementsByClassName (along with .getElementsByTagName and .getElementsByName) return node list objects (array-like containers). You can't interact with individual element properties and methods on node lists, you have to work with objects within the container. To set up event handlers on all the elements in the node list, you can loop through the container and set the handler one at a time.
Now, getElementsByClassName returns a "live node list", which is one that re-scans the document every time you interact with it to ensure that your container has the most up to date set of matching elements. This can cause big drops in page performance and the need for live node lists is pretty uncommon. Instead, use the more modern .querySelectorAll(), which allows you to pass any valid CSS selector in and returns a static node list.
// Get all the desired elements into a node list
let elements = document.querySelectorAll(".test");
// Convert the node list into an Array so we can
// safely use Array methods with it
let elementsArray = Array.prototype.slice.call(elements);
// Loop over the array of elements
elementsArray.forEach(function(elem){
// Assign an event handler
elem.addEventListener("click", function(){
console.log("You clicked me!");
this.style.backgroundColor = "#ff0";
});
});
<div class="test">Something</div>
<div>Something</div>
<div class="test">Something</div>
<div>Something</div>
<div class="test">Something</div>
You need to use .bind(thisArg[, arg1[, arg2[, ...]]]) in order to pass the current index and element (rif. this):
var bouton = document.getElementsByClassName('btn_inscription');
var formulaire = document.getElementsByClassName('formulaire');
var MyFonction = function(idx, event) {
formulaire[idx].style.display = 'block';
this.style.display ='none';
}
for (var i = 0; i < bouton.length; i++) {
bouton[i].addEventListener('click', MyFonction.bind(bouton[i], i));
// ^^^^^^^^^^^^^^^^^^^
}
.formulaire {
display: none;
}
<button class="btn_inscription">1</button>
<button class="btn_inscription">2</button>
<button class="btn_inscription">3</button>
<div class="formulaire">1</div>
<div class="formulaire">2</div>
<div class="formulaire">3</div>
You need to make use of this inside your event handler:
var buttons = document.getElementsByClassName('btn_inscription');
var MyFunction = function() {
this.closest('.formulaire').style.display = 'block';
this.style.display ='none';
}
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', MyFunction.bind(buttons[i]));
}

removing div from html in chrome extension

I am trying to remove the following div from a page with my chrome extension
HTML (TO REMOVE)
<div class="base-popup js-base-popup"><div class="js-obscurity base-popup__obscurity"></div>
<div class="base-popup__indent"></div>
<div class="base-popup__wrap">
<div class="base-popup__container clearfix base-popup__container -decor" style="width:500px;">
<i class="s-icon -m -close base-popup__close js-close"></i>
<div class="base-popup__content js-content"><div><div class="s-text">Sample Text.
<!-- close tag -->
</p>
<!-- close tag in translate -->
</div></div></div>
</div>
Here is the JS in my content script
function removeElementsByClassName(names) {
var els = document.getElementsByClassName(names),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('base-popup js-base-popup');
getElementsByClassName only accepts a single class name, but you're giving it two. Since the HTML you've shown only has a single element that has either of the two classes you're using, if that's the only element you want to remove, just pick one:
removeElementsByClassName("base-popup");
// or
removeElementsByClassName("js-base-popup");
Alternately, you could use querySelectorAll with a CSS selector:
function removeElementsBySelector(selector) {
var els = document.querySelectorAll(selector),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
Then if you want to remove elements that have either class:
removeElementsBySelector('.base-popup, .js-base-popup');
Or if you only want to remove a single element that has both classes:
removeElementsBySelector('.base-popup.js-base-popup');
And as this is a Chrome extension, you can do that rather more simply with Array.from, forEach, and Element#remove:
function removeElementsBySelector(selector) {
Array.from(document.querySelectorAll(selector)).forEach(element => {
element.remove();
});
}
your javascript is completely wrong. the right way:
function removeElementsByClassName(names){
names=names.split(" ");//you just get elems by one class so you need to split it into multiple operations
for(var a=1;a<names.length;a++){//ability to remove multiple classes
removeElementsByClassName(names[a]);
}
var els = document.getElementsByClassName(names[0]);
for (var i =0; i<els.length ; i++) { // its length not count
var element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('base-popup js-base-popup');
this removes all elements that contain one of these classes, if you wanted sth else see the other solution.

Having issue in changing style through JavaScript

Hi i am trying to change Display property of any HTML Tag with certain attribute..
But after many tries i am unable to change the tag properties.. My code is as below
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++)
{
if (allElements[i].getAttribute(attribute))
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
tags = getAllElementsWithAttribute('data-shares');
for(i=0;i<tags.length;i++)
{
tags[i].style.display = "none";
}
And the HTML has below Tag
<div class="shareTools" data-shares="facebook" data-url="#" data-title="Facebook" data-description="Facebook">
<div class="shareToolsBox">
<ul class="shareToolsList">
<li data-share="facebook">
<span>Facebook</span>
</li>
</ul>
</div>
</div>
Does anyone has any idea how to change Tag Style of any tag which has attribut i-e data-shares...
Change the function call to:
tags = getAllElementsWithAttribute('data-shares');
Here's it working on a JS Bin demo: http://jsbin.com/ufogExo/1/ The <div>s with the data-shares attribute are all hidden.
The problem was indeed the extra commas you had on your function call arguments.
I believe this does what you want:
function getAllElementsWithAttribute(attribute)
{
var items = document.querySelectorAll('['+attribute+']'),
i = items.length;
while ( i-- > 0 && (items[i].style.display = 'none') );
}
getAllElementsWithAttribute('data-shares');
see
http://jsfiddle.net/754zR/

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

How to hide all divs with JavaScript?

I am wondering how I can hide all divs on the page only using JavaScript, I cannot use jQuery. Is there a way to do this without using the arrays that comes with document.getElementByTag? Or if there is not, could you show me how to hide all?
Use getElementsByTagName() to get a list of all div elements, and then set their CSS display property to none:
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.display = 'none';
}
<div>sads</div>
<div>sads</div>
<span>not a div</span>
You will need to use document.getElementsByTagName, and then use a for loop to process all of the elements:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
divs[i].style.display = "none";
}
Just to put out a totally different solution here.
You could set a CSS class to your body, like this
body.hideDivs DIV {
display: none;
}
document.body.className = "hideDivs";
But this would hide everything inside those divs also, which might not be what you are going for here.

Categories