Find id of element where display property is block - javascript

Is it possible to return the id of an element which display property attribute is 'block'?

var nodeList = document.querySelectorAll("*"); // use an appropriate filter
var array = Array.prototype.slice.call(nodeList, 0);
var elements = array.filter(function (element) { return window.getComputedStyle(element).display === "block"; });
var ids = elements.map(function (element) { return element.id; });
The solution presented above searches the page for elements and then keeps only the ones which have a computed display of block. Works even if the style is not inline.

You can use:
Javascript
var divs = document.getElementsByTagName("div");
for (var i=0; i < divs.length; i++) {
display = divs[i].style.display;
if(display == 'block' ){
alert(divs[i].getAttribute('id'));
}
}
Html
<div id="1" style="display:block;">this is div 1</div>
<div id="2" style="display:block;">this is div 2</div>
<div id="3" style="display:none;">this is div 3</div>
Please refer to the fiddle: "http://jsfiddle.net/UAYWD/21/"

Pure Javascript:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if(divs[i].style.display == 'block'){
alert(divs[i].id);
}
}
.
<div id="div1" style="display:block;">Div 1</div>
<div id="div2" style="display:block;">Div 2</div>
<div id="div3" style="display:none;">Div 3</div>
Output:
div1
div2
Here's an example: http://jsfiddle.net/mhqwaxpw/

$("div").each(function(){
if($(this).css("display")=="block"){
alert($(this).attr('id'));
}
});

Related

Append child element in parent?

HTML elements are taken from the container. If the parent node has a child, make a button and insert child.id from child in the button. Everything works in the code, but does not want appendChild (h2);
It should look like:
<button id = "parent2"> <h2> child1 </h2> <h2> child2 </h2> </button>
<div id="container">
<div id="parent1"></div>
<div id="parent2">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</div>
</div>
<p id="demo"></p>
var parent = document.getElementById("container").querySelectorAll("*");
for (let i = 0; i < parent.length; i++) {
if(parent[i].hasChildNodes()){
var btn = document.createElement("BUTTON");
btn.id = parent[i].id;
document.getElementById("demo").appendChild(btn);
}
let children = parent[i].childNodes;
for (let i = 0; i < children.length; i++) {
if(children[i]){
var h2 = document.createElement("H2");
h2.innerHTML = children[i].id;
parent[i].appendChild(h2);
}else{}
}
}
There are many mistakes in your code:
This document.getElementById("container").querySelectorAll("*"); does select all children of a container (nested ones too).
You can not nest two loops that iterate over the same variable i.
childNodes does not return only the 3 divs you want, but also all the nodes that represent the spaces/newlines. You need to filter them out, here few possible solutions.
You require h2 tags to be inserted in the button, but you insert them in parent[i]
This should work:
var parent = document
.querySelectorAll("#container > *");
for (let i = 0; i < parent.length; i++) {
if(parent[i].hasChildNodes()) {
var btn = document.createElement("BUTTON");
btn.id = parent[i].id;
document.getElementById("demo").appendChild(btn);
let children = parent[i].childNodes;
for (let j = 0; j < children.length; j++) {
if (children[j].nodeName !== 'DIV') continue;
var h2 = document.createElement("H2");
h2.innerHTML = children[j].id;
btn.appendChild(h2);
}
}
}
<div id="container">
<div id="parent1"></div>
<div id="parent2">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</div>
</div>
<p id="demo"></p>

How do I count divs clicked using an event listener in javascript

I'm trying the count the total number of divs clicked and exactly which ones were clicked. I'm using an event listener because the onclick is already used. Let me clarify a bit more, first, here's my code:
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
.selected {
background: white;
}
var numClicked = document.querySelectorAll('.wrapper');
numClicked.forEach(numClicked =>
numClicked.addEventListener('click', clickedDivs)
)
function clickedDivs () {
i = 0;
numClicked.forEach(numClicked =>
i++
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + i;
}
What I'm trying to do with my javascript is count how many divs are selected. I'm also trying to tell exactly where ones were clicked. Let's say 1 and 2 were clicked, how do I find those were clicked and total number of divs clicked using js?
What you are doing wrong here is:
You are initialising i within the onClick event fn. which will always reset the value to 0 when ever the div will be clicked.
you are not storing anywhere which div is clicked
You are adding you'r listener on wrapper instead of .square (if you are not trying to get the value of clicked wrappers instead of clicked square)
So you can modify you'r javascript like this
<style>
.square{width: 100px; height: 100px; background: grey;}
.selected {
background: white;
}
</style>
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
<script>
var numClicked = document.querySelectorAll('.square');
numClicked.forEach(numClick => {
numClick.addEventListener('click', clickedDivs)
}
)
var itemsClicked = [] //to store which div is clicked
function clickedDivs (e) {
var value = e.target.innerHTML;
//edit
if(itemsClicked.indexOf(value) != -1) itemsClicked.splice(itemsClicked.indexOf(value), 1)
else
itemsClicked.push(value);
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + itemsClicked.join(",");
}
</script>
edit:
added to code to remove data from the list if already exist.
Rather than attach a handler to each div, you can use 1 window event listener. Give each clickable div an id that contains "clickable" so the event listener can filter out divs you aren't tracking. When you first click a tracked div, set its id as a key within a global object and assign 1 as the value; on additional clicks, increase value by 1.
const clicks = {};
window.addEventListener("click", (e)=> {
const id = e.target.id;
if(!id.includes("clickable"))return;
clicks[id]? clicks[id] += 1 : clicks[id] = 1;
console.log(clicks);
},)
<div class="wrapper">
<div id="clickable1" class="square">1</div>
<div id="clickable2" class="square">2</div>
<div id="clickable3" class="square">3</div>
</div>
My solution, I haven't tested it yet, test it and tell me how we adjusted it.
<div class="wrapper">
<div class="square" id="d-1">1</div>
<div class="square" id="d-2">2</div>
<div class="square" id="d-3">3</div>
</div>
<div id="result"></div>
var count = [];
var wrappers = document.querySelectorAll('.wrapper');
wrappers.forEach(square => square.addEventListener('click',() => onClickwrapperSquare(square.id));
function onClickwrapperSquare(id) {
var result = document.getElementById('result');
if(count.indexOf(id) == -1){
count.push(id);
}else{
count = count.slice(count.indexOf(id)+ 1);
}
result.innerHTML = `Squares selected: ${count.length}`;
}
This can be simply achieved by jQuery.
var count;
$(".square").click(function (){
count = count+1;
$("#dis").html(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class=square">1</div>
<div class="square">2</div>
<div class="square">3</div>
</div>
<div id="dis"></div>

javascript event fire only one

I am having a problem with the code below.
The code should handle the slider and changes between them when the img is
clicked, it works only once.
when I changed the onClick event to
document.getElementById("left").onclick = function(){
console.log("0");
}
It worked fine, but when I reverted, it doesn't change the slider more than once
snippet:
var index = 0;
document.getElementById("left").onclick = function(){
console.log("0");
}
document.getElementById("left").onclick = function(){
var slider = document.getElementsByClassName("slider");
slider[index].style.display = "none";
if(index == 0){ index = slider.length;}
slider[--index].style.display = "block";
}
document.getElementById("right").onclick = function(){
var slider = document.getElementsByClassName("slider");
slider[index].style.display = "none";
if(index >= slider.length){ index = 0;}
slider[++index].style.display = "block";
};
<div class="slider" style="display: block">
<div id = "left"><img src="Images/arrow-left.png" alt=""></div>
<div class="text">
<h2>welcome to the <span>classic</span></h2>
<p>Lorem ipsum is a name for a common type of placeholder text. Also known as filler or dummy text, this is simply copy that serves to fill a space</p>
</div>
<div id = "right"><img src="Images/arrow-right.png" alt=""></div>
</div>
thanks guys, the problem was that I gave multiple div the same ID which made the onclick event only fire once (with the first div only)

How to show div multiple step using javascript?

How to show div multiple step using javascript ?
i want to create code for
click on CLICK HERE first time it's will show one
click on CLICK HERE second time it's will show two
click on CLICK HERE third time it's will show three
click on CLICK HERE fourth time it's will show four
click on CLICK HERE fifth time it's will show five
http://jsfiddle.net/x53eh96o/
<style type="text/css">
div{
display: none;
}
</style>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
<div id="5">five</div>
<div onclick="myFunction()" style="display: block;">CLICK HERE</div>
<script>
function myFunction() {
document.getElementById("1").style.display = "block";
}
</script>
how can i do that ?
THANK YOU
First of all, it would be better to add a common class to your divs, in order to make the selection easier. Then you should select all of needed divs by class name, and pass through each of them, setting needed visibility.
http://jsfiddle.net/x53eh96o/7/
<div class="some_class" id="1">one</div>
<div class="some_class" id="2">two</div>
<div class="some_class" id="3">three</div>
<div class="some_class" id="4">four</div>
<div class="some_class" id="5">five</div>
<div onclick="myFunction()" style="display: block;">CLICK HERE</div>
<script>
var i = 0;
function myFunction() {
var divs = document.getElementsByClassName("some_class");
var divsLength = divs.length;
for(var j = divsLength; j--;) {
var div = divs[j];
div.style.display = (i == j ? "block" : "none");
}
i++;
if(i > divsLength) {
i = 0; // for a cycle
}
}
</script>
UPDATE
And here is jquery example: http://jsfiddle.net/x53eh96o/8/
<div class="some_class" id="1">one</div>
<div class="some_class" id="2">two</div>
<div class="some_class" id="3">three</div>
<div class="some_class" id="4">four</div>
<div class="some_class" id="5">five</div>
<div onclick="myFunction()" style="display: block;">CLICK HERE</div>
<script>
var i = 0;
function myFunction() {
var divs = $(".some_class");
divs.hide().eq(i).css({display: 'block'});
i++;
if(i > divs.length) {
i = 0;
}
}
</script>
id values should not start with a number.
div {
display: none;
}
<div id="show_1">one</div>
<div id="show_2">two</div>
<div id="show_3">three</div>
<div id="show_4">four</div>
<div id="show_5">five</div>
<div onclick="myFunction()" style="display: block;">CLICK HERE</div>
<script>
var show = 0;
function myFunction() {
try {
document.getElementById('show_' + ++show).style.display = "block";
} catch (err) {
show--
for (i = show; i > 0; i--) {
document.getElementById('show_' + i).style.display = "none";
show--;
}
}
}
</script>

How to get elements by style property value?

I need to get all div elements with "display: none" style and then remove all of these elements. Also i need to select just that divs which are contained in #somecontainer element. Have to do it in RAW javascript. Any idea?
example html:
<table id="listtabletemp">
<thead>
<tr id="theader">
<td id="theaderleft">loolz</td>
</tr>
</thead>
<tbody>
<tr class="" rel="13117025">
<td><div><style>
.ikthgjyhtr{display:none}
.tVOx{display:inline}
</style>
<div style="display:none">crap here</div>
<div></div>
<div></div>
<div style="display:none">crap here</div>
<div class="230">something good</div>
<div class="ikthgjyhtr">crap here</div>
<div style="display:none">crap here</div>
<div class="ikthgjyhtr">crap here</div>
<div style="display: inline">something good</div>something good
<div style="display: inline">something good</div>
<div class="21">something good</div>
<div style="display:none">crap here</div>
<div style="display:none">crap here</div>
<div style="display:none">crap here</div>
<div class="4">something good</div>
<div class="224">something good</div></div>
</td>
</tr>
</tbody>
</table>
Simple, the DOM is your friend:
function removeDivs() {
var container = document.getElementById("somecontainer");
var divs = container.getElementsByTagName("div");
var empty = [];
var getStyle = function(obj, css){
var style = null;
if(obj.currentStyle) {
style = obj.currentStyle[css];
} else if(window.getComputedStyle) {
style = window.getComputedStyle(obj, null).getPropertyValue(css);
}
return(style);
};
for(var i = 0, len = divs.length; i < len; i++) {
var div = divs[i];
if(div && ((div.style.display && div.style.display == "none") || getStyle(div, "display") == "none")) {
empty.push(div);
}
}
for(var i = 0, len = empty.length; i < len; i++) {
var div = empty[i];
div.parentNode.removeChild(div);
}
}
Quick and dirty, here's something to get you started:
http://jsfiddle.net/kttsJ/
var parent = document.getElementById('parent');
var items = parent.getElementsByTagName('DIV');
var hidden = [];
for (var i in items){
if ((items[i]).getAttribute !== undefined){
if ((items[i]).hasAttribute('style')){
if ((/display\:\s*none/gi).test(items[i].getAttribute('style'))){
hidden.push(items[i]);
}
}
}
}
for (var i in hidden){
hidden[i].parentNode.removeChild(hidden[i]);
}
This removes divs with the "display: none" style. I tested it on the OP's example. Note: I added a "some-container" id when testing.
function removeDivs() {
"use strict";
//Some container.
const someContainer = document.getElementById("some-container");
//Divs inside it.
const divsInside = someContainer.querySelectorAll("div");
//Loop, remove div if "display: none".
divsInside.forEach(function (divInside) {
const style = window.getComputedStyle(divInside);
if (style.display === "none") {
someContainer.removeChild(divInside);
}
});
}
removeDivs();

Categories