Any better way to hide multiple elements at once? - javascript

This works perfectly fine, but for future reference I would like to know if there is a better way to do this.
document.getElementsByTagName('h1')[0].style.display = 'none';
document.getElementsByTagName("p")[0].style.display = 'none';
document.getElementsByTagName("p")[1].style.display = 'none';
document.getElementsByTagName("ul")[0].style.display = 'none';
document.getElementsByTagName("hr")[0].style.display = 'none';
I'm open to using jQuery if it would help.

While jQuery wasn't specifically requested, it would be the shortest implementation to meet the OP's sample code exactly as written:
$('h1:eq(0), ul:eq(0), hr:eq(0), p:lt(2)').hide();

Keep your nodes in an Array, then you can write some functions which will hide or show a whole Array (or NodeList) at once, e.g.
function display_none(nodelist) {
var i = nodelist.length;
while (i-- > 0)
nodelist[i].style.display = 'none';
}
function display_default(nodelist) {
var i = nodelist.length;
while (i-- > 0)
nodelist[i].style.display = '';
}
So you have
var elms = [
document.getElementsByTagName('h1')[0],
document.getElementsByTagName("p")[0],
document.getElementsByTagName("p")[1],
document.getElementsByTagName("ul")[0],
document.getElementsByTagName("hr")[0]
];
Now can simply do
display_none(elms); // hide them all
display_default(elms); // return to default

Here's a pure Javascript option that implements a jQuery-like extension for the :lt(n) pseudo selector so you can specify however many of each tag you want.
As the question asked, this operates on the first two "p" tags, then the first "h1", "ul" and "hr" tags:
function hideItems(selector) {
var r = /:lt\((\d+)\)/;
selector.split(',').forEach(function(item) {
var len, elems, i, m = item.match(r);
if (m) {
item = item.replace(r, "");
elems = document.querySelectorAll(item);
len = Math.min(+m[1], elems.length);
} else {
elems = document.querySelectorAll(item);
len = elems.length;
}
for (i = 0; i < len; i++) {
elems[i].style.display = 'none';
}
});
}
hideItems('p:lt(2),h1:lt(1),ul:lt(1),hr:lt(1)');
Working demo: http://jsfiddle.net/jfriend00/m9vspymz/

Using Pure JavaScript
//gets all DOM elements with a tag of p or li
var elems = document.querySelectorAll('p,li');
//loops over all elements
for(var i = 0;i < elems.length; i++)
{
//hides each element in the array
elems[i].style.display = 'none';
}
Code Specifically for you
var elems = document.querySelectorAll('p,h1,ul,hr');
for(var i = 0;i < elems.length; i++)
{
elems[i].style.display = 'none';
}

Here's the code (JavaScript):
var n = [ // 'tagname',which in order
'h1',0,
'p',0,
'p',1,
'ul',0,
'hr',0
];
for(var i = 0;i < elems.length)
{
document.getElementsByTagName(n[i*2])[(n[i*2]+1)].style.display = 'none';
i++;
i++;
}

Related

How to use getElementsByTagName Effeciently

I'm currently using this bookmarklet to hide several random rows of a webpage:
(function () {
document.getElementsByTagName("tr")[1].style.display = "none";
document.getElementsByTagName("tr")[3].style.display = "none";
document.getElementsByTagName("tr")[6].style.display = "none";
})();
Is it necessary to repeat
document.getElementsByTagName("tr")[].style.display = "none"
again and again or is there any way to simplify it ?
I mean to merge all these into a simple command like
document.getElementsByTagName("tr")[1,3,6].style.display = "none".
Is it possible?
Kindly provide me an example coding for above bookmarklet?
Sure, you can store the trs in a variable:
var trs = document.getElementsByTagName("tr");
Then you can loop through the trs 1 through 3.
for(var i = 1; i <= 3; i++) {
trs[i].style.display = "none";
}
Alternately, you can use Array.prototype.slice to select a range of trs.
Array.prototype.slice.call(trs, 1, 4).forEach(function(tr) {
tr.style.display = "none";
});
Try this one
var rows= document.getElementsByTagName("tr")
Array.from(rows).forEach(v => v.style.display = 'none');
Use a for loop or foreach loop.
var temp = document.getElementsByTagName("tr");
for(var i = 0; i < temp.length; i++){
temp[i].style.display = "none";
}
or
var temp = document.getElementsByTagName("tr");
temp.forEach(element => element.style.display = "none");
Can be put into
document.getElementsByTagName("tr").forEach(element => element.style.display = "none");

expanding and collapsing folders

I need to get more than one element to toggle open and closed. Right now the function is just selecting the ID, but I'd like to know how to get it to select a class. I thought I could change the document.getElementById to document.getElementByClass but that didn't work.
I picked this bit of code during my search:
#ToggleTarget {display:hidden;}
<script type="text/javascript">
function Toggle() {
var el = document.getElementById("ToggleTarget");
if (el.style.display == "block") {
el.style.display = "none";
}
else {
el.style.display = "block";
}
}
</script>
var getElementsByClassName = function(node, classname) {
if (document.getElementsByClassName) {
return document.getElementsByClassName(classname);
}
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
var Toggle = function(){
var tp = getElementsByClassName(document.documentElement,'toggle');
for(var i = 0; i < tp.length; i++){
if(tp[i].style.display=='none')
tp[i].style.display='block'
else
tp[i].style.display='none'
}
}
Use getElementsByClassName and then loop through them.
EDIT
Just make sure they have the class toggle as used in my code above.
UPDATE
Added function for IE support (adopted from https://stackoverflow.com/a/7410966/600101).

jQuery ":contains()" analog for pure JS

I'm writing a script for CasperJS. I need to click on the link that contains a span with "1". In jQuery can be used :contains('1'), but what the solution is for selectors in pure Javascript?
HTML: <a class="swchItem"><span>1</span></a><a class="swchItem"><span>2</span></a>
jQuery variant: $('a .swchItem span:contains("1")')
UPD CasperJS code:
casper.then(function () {
this.click('a .swchItem *select span with 1*')
})
Since 0.6.8, CasperJS offers XPath support, so you can write something like this:
var x = require('casper').selectXPath;
casper.then(function() {
this.click(x('//span[text()="1"]'))
})
Hope this helps.
Try the following. The difference between mine and gillesc's answer is I'm only getting a tags with the classname you specified, so if you have more a tags on the page without that class, you could have unexpected results with his answer. Here's mine:
var aTags = document.getElementsByTagName("a");
var matchingTag;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].className == "swchItem") {
for (var j = 0; j < aTags[i].childNodes.length; j++) {
if (aTags[i].childNodes[j].innerHTML == "1") {
matchingTag = aTags[i].childNodes[j];
}
}
}
}
var spans = document.getElementsByTagName('span'),
len = spans.length,
i = 0,
res = [];
for (; i < len; i++) {
if (spans.innerHTML == 1) res.push(spans[i]);
}
Is what you have to do unless the browser support native css queries.
jQuery is javascript. There are also a number of selector engines available as alternatives.
If you want to do it from scratch, you can use querySelectorAll and then look for appropriate content (assuming the content selector isn't implemented) and if that's not available, implement your own.
That would mean getting elements by tag name, filtering on the class, then looking for internal spans with matching content, so:
// Some helper functions
function hasClass(el, className) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
return re.test(el.className);
}
function toArray(o) {
var a = [];
for (var i=0, iLen=o.length; i<iLen; i++) {
a[i] = o[i];
}
return a;
}
// Main function
function getEls() {
var result = [], node, nodes;
// Collect spans inside A elements with class swchItem
// Test for qsA support
if (document.querySelectorAll) {
nodes = document.querySelectorAll('a.swchItem span');
// Otherwise...
} else {
var as = document.getElementsByTagName('a');
nodes = [];
for (var i=0, iLen=as.length; i<iLen; i++) {
a = as[i];
if (hasClass(a, 'swchItem')) {
nodes = nodes.concat(toArray(a.getElementsByTagName('span')));
}
}
}
// Filter spans on content
for (var j=0, jLen=nodes.length; j<jLen; j++) {
node = nodes[j];
if ((node.textContent || node.innerHTML).match('1')) {
result.push(node);
}
}
return result;
}

How to hide a class using javascript?

I have text on a page, its in a <h3> tag, which has a class ms-standardheader, but there are other texts on the page with the same class in its own <h3> tag. I also know the text I want to hide is 'Session'.
With this how can I write a javascript function to hide only this text?
Here is an image of the developtools from IE.
I'd suggest, if you're restricted (as your tags suggest) to non-library plain JavaScript, the following:
var h3s = document.getElementsByTagName('h3'),
classedH3 = [];
for (var i = 0, len = h3s.length; i < len; i++) {
if (h3s[i].className.indexOf('ms-standardheader') > -1) {
classedH3.push(h3s[i]);
}
}
for (var i = 0, len = classedH3.length; i < len; i++) {
if (classedH3[i].firstChild.nodeValue == 'the text to hide'){
classedH3[i].style.display = 'none';
}
}​
JS Fiddle demo.
References:
push().
document.getElementsByTagName().
element.className.
node.nodeValue.
indexOf().
Can't you give the target element an ID? That would make things much more simple. Otherwise, you have to go through all <h3> elements until you find the one you want to hide:
var headings = document.getElementsByTagName("h3");
for(var i=0; i<headings.length; i++) {
var contentElement = headings[i].getElementsByTagName('nobr');
var content = "";
if(contentElement.length) {
content = contentElement[0].textContent ? contentElement[0].textContent : contentElement[0].innerText;
}
var content = contentElement.length ? contentElement[0].childNodes[0].nodeValue : '';
if(headings[i].className == 'ms-standardheader' && content == 'Session') {
headings[i].style.display = 'none';
}
}
you should try this :
window.onload = function()
{
getElementByClass('ms-standardheader');
}
window.getElementByClass = function(theClass){
var allHTMLTags=document.getElementsByTagName('*');
for (i=0; i<allHTMLTags.length; i++) {
if (allHTMLTags[i].className==theClass) {
var content = allHTMLTags[i].innerHTML;
var search = /session/;
if (search.test(content))
{
alert(search);
allHTMLTags[i].style.display='none';
}
}
}
}
See Demo : http://jsfiddle.net/3ETpf/18/
Always favour a unique Id where possible. If not possible then you have to manually traverse the DOM to find the elements you are looking for. Here's an example using getElementsByTagName().
var i, header, headers = document.getElementsByTagName('h3');
for (i = 0; i < headers.length; i += 1) {
header = headers[i];
if (header.className === 'ms-standardheader' &&
(header.textContent || header.innerText) === 'Session') {
header.style.display = 'none';
}
}
see: http://jsfiddle.net/whP5z/
If you have jquery you may type this :
$("h3.ms-standardheader:contains('Session')").hide();

Hide/Show Table Columns with Javascript (fix for all browsers?)

I have a long table with many many columns and it looks really ugly for the users. What I wanted to do was create a simple button that would act as a switch, to turn on and off some of the columns.
Some of the columns are not needed, so what I did was add a class to every that wasn't needed, eg: ....
Now, what I thought I could do was this:
var hidden = 1;
function toggleTable(){
element_array = document.getElementsByClassName('disabled');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
This works for the most part in Firefox, but some quick tests in IE(7+8) and I get the following:
Message: Object doesn't support this property or method
Obviously indicating that IE doesn't want to let me simply change "display: none;" for something like table columns/rows.
I can't think of any workarounds. Ideally I'd like a fully cross-compatible solution to toggling the display of certain table columns,but if it's not compatible in the older browsers (eg: IE6) then that would also be OK.
The error that you're getting is not because IE doesn't want to set the display property, it's because the getElementsByClassName method isn't implemented in IE. If you want an implementation of that methods you can use this one which was written by Dustin Diaz.
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you would re-write your method as follows.
var hidden = 1;
function toggleTable(){
var element_array = getElementsByClass('foo');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
toggleTable();
And what about jQuery.toggle()?
$(".disabled").toggle();

Categories