I want to hide the <h1>
element using plain javascript, not jQuery, without adding id="whatever"
or class="whatever"
to the tag. Is this possible?
Why can't I just add id="whatever" to the tag?
I'm using a UIButton in xCode that when clicked, it injects javascript into a UIWebView. Inside that UIWebView is a H1 element that is on a website that I do not have access to to add <h1 id="whatever">
. I hope it makes sense.
I want to hide the <h1>
element using plain javascript, not jQuery, without adding id="whatever"
or class="whatever"
to the tag. Is this possible?
Why can't I just add id="whatever" to the tag?
I'm using a UIButton in xCode that when clicked, it injects javascript into a UIWebView. Inside that UIWebView is a H1 element that is on a website that I do not have access to to add <h1 id="whatever">
. I hope it makes sense.
5 Answers
Reset to default 8document.getElementsByTagName('h1')[0].style.display = 'none';
You can use getElementsByTagName
method:
var h = context.getElementsByTagName('h1');
for (var i = h.length; i--; ) {
h[i].style.display = 'none';
}
Where context
is document
or more specific parent node you want to search your headers within.
However there is better solution. You could add specific class to some parent node and hide child headers with CSS:
.without-headers h1 {display: none;}
Use getElementsByTagName
to hide the first h1
on your page:
document.getElementsByTagName("h1")[0].style.display = "none";
// ^ index 0, so that's the first `h` that's found.
Or to hide them all:
var headers = document.getElementsByTagName("h1");
for (var i = 0, l = headers.length; i < l; i++; ) {
headers[i].style.display = "none";
}
Or even better yet, if you can modify the CSS:
h1{
display:none;
}
For the JavaScript solutions, please keep in mind that they will only work when the DOM has been loaded.
Add a domready
event listener, like this:
window.addEvent('domready', function() {
// modify your DOM here.
});
you can use getElementsByTagName
document.getElementsByTagName("h1")
But it will access all h1
elements, so to be more specific access it by index
like this
document.getElementsByTagName("h1")[0].style.display = "none";
just small change in dfsq's code
var h = document.getElementsByTagName('h1');
for (var i =0; i<h.length; i++) {
document.getElementsByTagName('h1').item(i).style.display = 'none';
}
getElementsByTagName()
returns anarray
of elements. You forgot the index. – Cerbrus Commented Feb 12, 2013 at 9:14<style>h1{display:none}</style>
– David Hellsing Commented Feb 12, 2013 at 9:17