简体   繁体   中英

How to hide and show div element by id in a WordPress page?

I have a number of div elements on my page. I want to hide them all except for when they are clicked. When clicked, they should show. I have followed a number of examples found on SO. However, I can't seem to get any of them to work on my wordpress page, without multiple clicks. What am i doing wrong.

FYI, the code below is placed exactly as seen, into a Wordpress page.

 function toggle_visibility(id) { var e = document.getElementById(id); if (e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } 
 <strong><a href="#" onclick="toggle_visibility('list_one');">List One</a></strong> <div id="list_one" style="display: none"> <ul> <li>Item One</li> <li>Item Two</li> <li>Item Three</li> <li>Item Four</li> <li>Item Five</li> </ul> </div> <strong><a href="#" onclick="toggle_visibility('list_two');">List Two</a></strong> <div id="list_two" style="display: none"> <ul> <li>Item Uno</li> <li>Item Dos</li> <li>Item Tre</li> </ul> </div> 

you want to hide all div tags on single click? then you can try this

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#list_one,#list_two {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color:#C5C5C3 ;
  margin-top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="list_one">
<ul>
    <li>Item Uno</li>
    <li>Item Dos</li>
    <li>Item Tre</li>
</ul>
</div>

<div id="list_two">
<ul>
    <li>Item Uno</li>
    <li>Item Dos</li>
    <li>Item Tre</li>
</ul>
</div>

<script>

function myFunction() {

var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
    if (divs[i].style.display === "none") {
    divs[i].style.display = "block";
  } else {
    divs[i].style.display = "none";
  }       
}
}
</script>

</body>
</html>

for single div try below javascript

function myFunction() {
  var x = document.getElementById("list_one");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

You could try:

function toggle_visibility(id) {
  var e = document.getElementById(id);
  e.style.display = e.style.display == 'none' ? '' : 'none';
}

However, as a previous commenter said, your code does actually work.

If you are using jQuery you could do:

$('#list_one').toggle();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM