admin管理员组

文章数量:1289874

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, i.e. 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>

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, i.e. 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>
Share Improve this question edited Feb 16, 2015 at 2:33 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Mar 18, 2014 at 17:52 user3265963user3265963 2733 gold badges11 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You could use the following:

EXAMPLE HERE

<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.

EXAMPLE HERE

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:

EXAMPLE HERE

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().

EXAMPLE HERE

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);

本文标签: javascriptHiding a div when link is clickedStack Overflow