user3164083
user3164083

Reputation: 1073

hide html element using javascript

JavaScript:

function hide_article() {
    var htmlElement = document.getElementsByTagName("article")[0];
    htmlElement.setAttribute("visibility", "hidden");
    console.log("hiding");
};

HTML:

<div id="right-hand-side">
   <img src="resources/Logo.png" onmouseover="hide_article()" onclick="hide_article()"/>
</div>

This function is being called but the article is not being hidden. Any idea why? Cheers.

Upvotes: 3

Views: 4847

Answers (2)

Mitya
Mitya

Reputation: 34556

Yes - visibility is a CSS rule name, not an HTML attribute.

htmlElement.style.visibility = 'hidden';

Bear in mind, though, that, unless you have good reason to use visibility (and there are some), you'd normally hide elements via display (= 'none') rather than via visibility.

Also, you're assuming that your function will find an element. If it doesn't, your code will error. Best to check this first:

function hide_article() {
    var htmlElements = document.getElementsByTagName("article");
    if (htmlElements.length) { //<-- check before continuing
        htmlElements[0].style.visibility = "hidden";
        console.log("hid element");
    }
};

Upvotes: 7

Alexander Vieth
Alexander Vieth

Reputation: 876

This is the statement that you want:

htmlElement.style.visibility = 'hidden';

Upvotes: 2

Related Questions