I am working on a site and need to only show a div if the title = "something". I cannot seem to achieve it, I have tried jQuery and javascript, here is what I have now.
var title = document.getElementsByTagName("title")[0].innerHTML;
console.log(title);
document.getElementsByClassName("book-a-lane").elems[0].style.visibility= "hidden";
if(title === "Frisco, TX"){
document.getElementsByClassName("book-a-lane").elems[0].style.visibility= "block";
}
You can get the title much more easily via document.title
.
You're inventing a property here:
document.getElementsByClassName("book-a-lane").elems[0]
// --------------------------------------------^^^^^
getElementsByClassName
returns a list, it doesn't have an elems
property. Also note that getElementsByClassName
isn't as well supported as querySelector
, which would be more useful here.
You can also simplify the code dramatically.
Here's an example:
document.querySelector(".book-a-lane").style.visibility =
document.title === "Frisco, TX" ? "visible" : "hidden";
querySelector
takes a CSS selector and returns the first matching element (or null
). There's also querySelectorAll
, which returns a list of matching elements.
You might want document.title.trim()
, but beware browser support for it.
The title
variable's value can be fetched with this: var title = document.title
.
The line inside your if
statement is faulty because there's no such thing as visibility: block;
. It's either display: block;
or visibility: visible;
.
This is the semi-improved version:
var title = document.title;
document.getElementsByClassName("book-a-lane")[0].style.visibility = "hidden";
if (title == "Frisco, TX") {
document.getElementsByClassName("book-a-lane")[0].style.visibility = "visible";
}
You don't need to use .elms
to access the elements.
You can even use the ?
strategy to do a true/false switch:
document.getElementsByClassName("book-a-lane")[0].style.visibility = title == "Frisco, TX" ? "visible": "hidden";
Do you mean to do this?
var title = document.getElementsByTagName("title")[0].innerHTML;
document.getElementsByClassName("book-a-lane")[0].style.visibility="hidden";
if(title === "Frisco, TX"){
document.getElementsByClassName("book-a-lane")[0].style.visibility= "block";
}
Notice the lack of elems
. getElementsByClassName
can be accessed with the array accessor directly.
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.