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.
Related
I'm making a tree structure using html and css.
This is the final structure that I should reach: http://jsfiddle.net/yrE7N/1/
What I need is, on clicking a node, its children node will appear.
I've done this till now:
JS Fiddle: http://jsfiddle.net/ZTkLg/11/
I've used this JS function
var _hidediv = null;
function showdiv(id) {
if(_hidediv)
_hidediv();
var div = document.getElementById(id);
div.style.display = 'block';
_hidediv = function () { div.style.display = 'none'; };
}
The thing is, the JS function doesn't seem to be toggling the visibility of the div stage-two.
I've used this function before on this page: http://leonardorestaurant.in/menu and it worked but I can't figure the problem out in this case.
Try
Some text here
and
var flag = true;
function showdiv(id) {
var div = document.getElementById(id);
div.style.display = flag ? 'none' : 'block';
flag = !flag;
}
Demo: Fiddle
The console in my browser prints out :
Uncaught TypeError: Cannot read property 'style' of null
Which means that here :
div.style.display = 'block';
div is not the result you think it should be... That tells us that id is not what we think here :
var div = document.getElementById(id);
Which I confirmed by using :
console.log(id);
inside your function.
The id value is actually the <div id="two">
So, basically you already have the element you're looking for.
However, you've got bigger problems, which is that you need a toggle function, I'm just guessing. Try using this :
function toggleDiv(id) {
var el = document.getElementById(id);
var newDisplayValue = "none";
if ( el.style.display && el.style.display === "none" ) {
newDisplayValue = "block";
}
el.style.display = newDisplayValue;
}
and change to this :
<a href=# onclick="toggleDiv('two');">
see it here
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();
}
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>
I'm trying to modify this code to also give this div item an ID, however I have not found anything on google, and idName does not work. I read something about append, however it seems pretty complicated for a task that seems pretty simple, so is there an alternative? Thanks :)
g=document.createElement('div'); g.className='tclose'; g.v=0;
You should use the .setAttribute() method:
g = document.createElement('div');
g.setAttribute("id", "Div1");
You can use g.id = 'desiredId' from your example to set the id of the element you've created.
var g = document.createElement('div');
g.id = 'someId';
You can use Element.setAttribute
Examples:
g.setAttribute("id","yourId")
g.setAttribute("class","tclose")
Here's my function for doing this better:
function createElement(element, attribute, inner) {
if (typeof(element) === "undefined") {
return false;
}
if (typeof(inner) === "undefined") {
inner = "";
}
var el = document.createElement(element);
if (typeof(attribute) === 'object') {
for (var key in attribute) {
el.setAttribute(key, attribute[key]);
}
}
if (!Array.isArray(inner)) {
inner = [inner];
}
for (var k = 0; k < inner.length; k++) {
if (inner[k].tagName) {
el.appendChild(inner[k]);
} else {
el.appendChild(document.createTextNode(inner[k]));
}
}
return el;
}
Example 1:
createElement("div");
will return this:
<div></div>
Example 2:
createElement("a",{"href":"http://google.com","style":"color:#FFF;background:#333;"},"google");`
will return this:
google
Example 3:
var google = createElement("a",{"href":"http://google.com"},"google"),
youtube = createElement("a",{"href":"http://youtube.com"},"youtube"),
facebook = createElement("a",{"href":"http://facebook.com"},"facebook"),
links_conteiner = createElement("div",{"id":"links"},[google,youtube,facebook]);
will return this:
<div id="links">
google
youtube
facebook
</div>
You can create new elements and set attribute(s) and append child(s)
createElement("tag",{attr:val,attr:val},[element1,"some text",element2,element3,"or some text again :)"]);
There is no limit for attr or child element(s)
Why not do this with jQuery?
var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})
var element = document.createElement('tagname');
element.className= "classname";
element.id= "id";
try this you want.
that is simple, just to make a new element with an id :
var myCreatedElement = document.createElement("div");
var myContainer = document.getElementById("container");
//setAttribute() is used to create attributes or change it:
myCreatedElement.setAttribute("id","myId");
//here you add the element you created using appendChild()
myContainer.appendChild(myCreatedElement);
that is all
I'm not sure if you are trying to set an ID so you can style it in CSS but if that's the case what you can also try:
var g = document.createElement('div');
g.className= "g";
and that will name your div so you can target it.
window.addEventListener('DOMContentLoaded', (event) => {
var g = document.createElement('div');
g.setAttribute("id", "google_translate_elementMobile");
document.querySelector('Selector will here').appendChild(g);
});