I am trying to create a div with some text. Then there is a link below and when clicked the div should hide. This should be only be java script, ie no Jquery
See my try at below.. Is it possible to do it somehow inside the a element? Do I have to create a function inside a JD script?
<div id="text">
Lorem Ipsum blablal b blablaba balbla bla.
</div>
<a href="#" onclick="document.getElementById('text').hidden">Click me to hide the div</a>
You could use the following:
<a href="#" onclick="document.getElementById('text').style.display = 'none'">...</a>
Alternatively, if you want to use unobtrusive JavaScript, this would work if you add an id
to the link.
document.getElementById('link').addEventListener('click',function(){
document.getElementById('text').style.display = 'none';
});
The above examples hide the link with display:none
. If you would rather remove the element:
document.getElementById('link').addEventListener('click',function(){
document.getElementById('text').remove();
});
If you want to toggle the visibility and hide/show the element, you could use .classList.toggle()
.
document.getElementById('link').addEventListener('click',function(e){
document.getElementById('text').classList.toggle('hidden');
});
CSS
.hidden {
display:none;
}
Just take the support this method has into consideration.
Using this code will let you hide/show the div whitout having to add any <script>
tag or JavaScript library.
<div id="text" style="display: block">
Lorem Ipsum blablal b blablaba balbla bla.
</div>
<a href="#" onclick="document.getElementById('text').style.display === 'block' ? document.getElementById('text').style.display = 'none' : document.getElementById('text').style.display = 'block'">Click me to hide the div</a>
josh is right, just add a third argument to the addEventListener as false to capture the event in bubbling phase
document.getElementById('link').addEventListener('click',function(){
document.getElementById('text').style.display = 'none';
}, false);
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.