I want to change display without documentGetElementById if possible but the following is not working. html
<a href="javascript:void();" onclick="toggleFaq('1')">Instructions</a><div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
javascript:
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
divname.style.display="block";
}
Can anyone tell me what I am doing wrong?
Thank you.
I can't get why you do not want to use getElementById
, but...
If you have elements in order like this
<a href="javascript:void();" onclick="toggleFaq('1')">Instructions</a>
<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
<a href="javascript:void();" onclick="toggleFaq('2')">Instructions</a>
<div id="showfaq2" style="display:none;">Open Box. Remove device. </div>
...
<a href="javascript:void();" onclick="toggleFaq('N')">Instructions</a>
<div id="showfaqN" style="display:none;">Open Box. Remove device. </div>
You may use
<a href="javascript:void();" onclick="toggleFaq(this)">Instructions</a>
function toggleFaq(obj) {
obj.nextElementSibling.style.display = 'block';
}
In your code divname
is a variable containing a string "showfaq1", which doesn't have style
property.
To change the style of an element you need a reference to that element which you can obtain using document.getElementById(divname)
:
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
document.getElementById(divname).style.display="block";
}
If you have an allergy to document.getElementById
, you may use document.querySelector('[id="' + divname +'"]');
, but its support is not as good as the former, and it's slower.
Posting a separate answer as it has no impact on my previous one. But you could make the base mechanism without JS at all, then use one of the JS-based solutions to fix it in broken browsers if needed:
HTML
<a href="#showfaq1">Instructions</a>
<div id="showfaq1">Open Box. Remove device. </div>
CSS
a + div { display:none; }
a:focus + div, a + div:target { display:block; }
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.