I am looking for javascript (not jquery as client has specified) to hide a div with class=top, if the div has no content. I can do it using jquery like below, but need to use javascript. Any ideas please?
$('div.top:empty').hide();
Something like:
var top = document.getElementsByClassName("top");
for (var i = 0; i < top.length; i++) {
if (top[i].innerHTML.length == 0)
top[i].style.display = "none";
}
you could use innerHTML property to check if the selected div.top element contains content. something like this.
var topDiv = document.getElementsByClassName('top')[0];
if(topDiv.innerHTML === '') {
topDiv.style.display = 'none';
}
(if(document.getElementById("yourDiv").innerHTML=="")
{
document.getElementById("yourDiv").style.display='none';
}
You need to give id to DIV which you want to hide As there are no function in javascript by which you can find div by class.
HTML:
<div class="top" id="divId"></div>
Javascript:
if( document.getElementById("divId").innerHTML == "" )
{
document.getElementById("divId").style.display='none';
}
Use the following script:
var divContent = $('div .top')[0].innerHTML;
if (divContent === '')
{
$('div .top').hide();
}
Related
I have a working grid that show a cell for every title in the json:
async function loop_iteration(json, i, arr) {
arr.push(`<a onClick="show()" class="cell" id=${i}"><div >${json[i].title}</div> </a>`)
arr.push(`<div class="info" id=${i}>${json[i].title}<br><br><br><br><br>Game Size: ${json[i].size}<br><br>Last Update: ${json[i].date}</div>`)
}
I want to show on click of the class info.
The problem is that it gives always the same title(first), it's like is always the first cell to be clicked
I show the info div like this:
<script>
function showinfo() {
var node = document.querySelector('.cell.info')
var visibility = node.style.visibility;
node.style.visibility = visibility == "visible" ? 'hidden' : "visible"
}
</script>
while if i show the div using this:
function show(){
var divsToHide = document.getElementsByClassName("info");
for(var i = 0; i < divsToHide.length; i++)
{
divsToHide[i].style.visibility="visible";
}
//document.getElementsByClassName('info')['${i}'].style.visibility = 'visible';
}
happen something strange, the div showed is not the first but is like it show all the div
Thanks for any help.
I find out the problem.
It was the javascript, so i extract the id and then iterate the class with the id
function show(clicked_id){
clicked_id = parseFloat(clicked_id);
document.getElementsByClassName('info')[clicked_id].style.visibility = 'visible';
}
i know how to do it with jquery, but how with clean javascript? Any help how to do this?
Here is my code
var element = document.getElementsByTagName('tagone')[0];
if(element !== null){
document.getElementByClassName('classsix')[0].style.display = 'none';
}
You can use the hidden DOM attribute or create a new class called hide and use the logic accordingly.
var element = document.querySelector('tagone'); // returns only first match
if(element) {
document.querySelector('.classsix').setAttribute('hidden',true);
}
or you can create the class in css .hide { display: none; } and use document.querySelector('.classsix').classList.add('hide');
your code is right.
you can use like this also
var element = document.getElementsByTagName('tagone')[0];
var element1= document.getElementsByClassName('classsix')[0];
if(element && element1){
element.style.display = 'none';
}
I tried this and it's working.
if (document.getElementsByTagName('tagone')[0] != null) {
document.getElementsByTagName('classix')[0].style.display = 'none';
}
The javascript function is getElementsByClassName you missed 's'
function hide(){
var y = document.getElementsByClassName("x");
y[0].style.display = 'none'
}
Here is the jsfiddle link.
I'm trying to make a site where users can create there own social networking buttons. (I know its been done but its mostly for practice). A part of the site will allow users to choose the shape of the buttons. Here is the HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
What I would like to do is add an event listener when the div is clicked. After it's clicked the class attribute would be changed to "selected." When another one would be click then the first clicked one would be cleared and the next one would be selected. Just like with radio buttons.
I am familiar with JavaScript and my idea was this:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}
A more simple version of scdavis41's answer:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
I also put a selector that includes the control's main div id in case you want to put this control more then once in your page.
** EDIT **
If you absolutly want to use javascript and DOM try this:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);
This is verbose, but you could use:
$(document).ready(function(){
$('#square').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#circle').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#rounded').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
This is jQuery, which means you have to load the jQuery library, but putting this above your script tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
If you are looking for a pure JavaScript solution, you could try this:
if(option == 'add'){
element.className = element.className + ' selected';
element.onclick = function() {select(this.id, 'remove')};
element.innerHTML = '✓';
}
else if(option == 'remove'){
element.className = element.className.replace(/\bselected\b/,'');
element.onclick = function() {select(this.id, 'add')};
element.innerHTML = '';
}
JSFiddle: http://jsfiddle.net/hKePD/
**EDIT**
Or if you were looking for a checkbox to be always checked, you could try this: http://jsfiddle.net/hKePD/1/
Building on scadvis41's answer, this is much shorter:
$(document).ready(function(){
$('.shapeSelect').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
No idea where the problem lies, tried various things and I'm not having any luck. I've done this successfully before in the past but now it won't work, any help would be great...
HTML snippet:
<tr>
<td class="tableContent noBorderSides paddingAll"><img class="imgResize" src="images/emptyCircle.png" onclick="expandItem()"/>
<div id="Expand" class="hiddenDiv">
HELLO?
</div>
JavaScript:
function expandItem() {
if (document.getElementById("Expand").style.display == 'block') {
document.getElementById("Expand").style.display = 'none';
}
else if (document.getElementById("Expand").style.display == 'none') {
document.getElementById("Expand").style.display = 'block';
}
}
CSS:
.hiddenDiv {
display: none;
}
What am I doing wrong?
The initial display that is set in your CSS won't be reachable from the .style property.
Do it like this:
function expandItem() {
var expand = document.getElementById("Expand");
if (expand.style.display == '') {
expand.style.display = 'block';
}
else if (expand.style.display == 'block') {
expand.style.display = '';
}
}
Or a little shorter like this:
function expandItem() {
var expand = document.getElementById("Expand");
expand.style.display = (expand.style.display == '') ? 'none' : '';
}
Use .getComputedStyle() to get any style attributes associated with a given element. Notice, that the object returned is read only, so you'll want to use this for the initial if statement, and then set the style as you were doing above.
You could just remove the class from the element that defines the hidden property and add when you want to hide:
if (document.getElementById("Expand").className == '') {
document.getElementById("Expand").className = 'hiddenDiv';
}
else if (document.getElementById("Expand").className == 'hiddenDiv') {
document.getElementById("Expand").className = '';
}
Do note that if you have other classes on that element you will need to do a little string manip rather than just a straight check and remove.
//Temporary solution
//Replace your javascript code with following code
if (document.getElementById("Expand").style.display == 'block') {
document.getElementById("Expand").style.display = 'none';
}
else{
document.getElementById("Expand").style.display = 'block';
}
//Note :- Javascript detect '' (empty) when it try to search display property for expand block
#user1689607's answer is right if you need to just use javascript. If you have access to jQuery you can do it like so
$("#Expand").toggle();
And a simple jsfiddle to demonstrate: http://jsfiddle.net/P36YA/
I use this script :
<script language="javascript">
function toggle() {
var ele = document.getElementById("mydiv");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
Called by :
echo '<a id="displayText" href="javascript:toggle();">show</a>';
i want to show / hide several div (not in a list or a form)
i try :
var ele = document.getElementById("mydiv", "mydiv2");
but it's showing and hidding only the first div
Description
This is not jQuery. You should use the jQuery functions to guarantee cross browser compatibilty.
Check out my sample and this jsFiddle
Sample
<div id="mydiv">test</div>
<div id="displayText">test2</div>
$(function() {
$("#displayText").click(function() {
$("#mydiv").toggle();
});
});
More Information
jsFiddle
jQuery.toggle()
jQuery.click()
The getElementById() function accepts a single argument, so you cannot pass it a list of ids. There are a number of options, I suggest two of them:
Use an array of divs and iterate through it, e.g.
var divs = [ 'mydiv1', 'mydiv2', ... ];
for ( var i = 0; i < divs.length; i++ ) {
var div = document.getElementById( divs[ i ] );
...
}
Use a library such as jQuery that lets you operate on lists of items easily. In that case you could mark all your divs with an appropriate class, e.g. myclass, and use something like:
$(".myclass").hide()
If you can use include jQuery in your page then use jQuery instead of pure javascript to make your life simpler. Try this
function toggle() {
var ele = $("#mydiv");
var text = $("#displayText");
if(ele.is(':visible')) {
ele.hide();
text.html("show");
}
else {
ele.show();
text.html("hide");
}
}
If you want to select multiple element in jQuyer then you can pass multiple selectors seperated by a comma.
var elems = $("#mydiv, #mydiv1, #mydiv2");
elems.show();//Will show all the selected elements
elems.hide();//Will hide all the selected elements
If you want to do it in plain javascript, you could try something like this:
<script type="text/javascript">
var elements = [ 'mydiv', 'mydiv2' ]
foreach ( elem in elements )
{
var e = document.getElementById(elem);
// show/hide here
}
</script>