What is the better performance way to hide HTML elements? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
If I have many following divs:
<div class="error"> </div>
<div class="error"> </div>
<div class="error"> </div>
<div class="error"> </div>
<div class="error"> </div>
...
What is the best way (and best practice) to hide them all at once?
$('.error').hide() or
.addClass('hide') including .hide { display: none; } ?

Best is an opinion, you can run jsperf tests and each browser will be different.
In the end you will either loop in JavaScript and add classes or set style attributes or just rely on the CSS to do the looping for you.
Look at using a selector
$(".error").hide(); // or .addClass() or .css("display","none")
Under the covers it does:
a DOM lookup for one or more elements
it is doing a for loop over the set
it gets the current element in the loop iteration
Applys a css rule in the loop iteration
Ends up doing a redraw/repaint
But one way to not have to loop is to just rely on adding a CSS rule higher up in the hierarchy.
CSS:
.hideErrors div.error {
display: none;
}
JavaScript:
$(document.body).addClass("hideErrors");
What this does:
DOM lookup for one element
Adds one class
Ends up doing a redraw/repaint
This way you do not have to loop through and add a class to every element. It would be better to place the "hideError" rule around the element that wraps the error list. So change "body" to that parent element.

It really doesn't matter which you pick. If it's that important to you, run a benchmark.
Most of the browser's time would be handling layout and repaint anyway, the addition of class or inline style (Because that's what .hide() does, add style="display: none; to the element) really doesn't matter either way.
If you care about performance, drop jQuery, start using some vanilla JS, learn about page performance and optimize your JavaScript and CSS selectors.
Honestly, how you modify the DOM is the last thing you should be worrying about :)

The term best isn't really enough information, because it can mean performance (speed) or size (included libraries).
If you already are using JQuery, it is generally a very efficient library and the following is how you would do that after the DOM finished loading.
$( document ).ready(function() {
$('.error').hide()
});
There are other events besides 'DOM ready' that JQuery defines that you can hook the action up to, which is why its a convenient library.
If you are just interested in overall speed and want to avoid external libraries, CSS is generally your fastest way to go, and you would add the class as you stated in your Style Sheet. This limits when you can hide them to before the DOM loads.
There are best and worst cases for all of the situations you described. Javascript will have to loop (parse) through the DOM so it will always be slower than pure CSS.

I think add and remove class will be better way to handle this.
In this way you can also do other styling changes related to error message.
css code :
.showdiv {
display : block;
}
.hidediv {
display:none;
}
javascript code :
$('.error').addClass('showdiv')
$('.error').removeClass('hidediv')

If you would like them hidden on page load add a class hidden to the divs.
.hidden{
display: none;
}
To show and hide just use jquery.
$('.error').hide();
$('.error').show();

Related

javascript select by CSS and toggle display [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a javascript newbie so go easy on me. I'm wanting to select a bunch of text that is identifiable only by inline CSS (not classes or ids or anything), and create a toggle that turns it on and off. So -- find everything with backgroundColor = '#eed6b4' and toggle display='none' / 'inline-block'
Needing the javascript and html... thx
=====================
This is what I tried originally:
<script type="text/javascript">
function toggleVisibility() {
var codeNum = document.getElementsByClassName('syntaxHighlightingPlugin');
i = codeNum.length;
while(i--) {
codeNum[1].style.backgroundColor = '#eed6b4';
if(codeNum.style.display == 'inline-block')
codeNum.style.display = 'none';
else
codeNum.style.display = 'inline-block';
}
}
</script>
<button type="button" onclick="toggleVisibility();"> Hide numbers (for copying) </button>
Oh, and as I replied to a comment, the twist on this is that it's for text rendered by a TWiki plugin, so I have no control over the resulting CSS --- which, as I said, has no classes --- also, since it's rendered, I think I may need to use something like getComputedStyle (?).
It's generally bad practice to use inline css, and to make your Javascript dependant on that inline CSS is also not a good idea. However, if you wanted to select an element based on the value of an attribute, you can use the attribute value selector like this:
$("[style='backgroundColor *= #eed6b4']").hide();
Reminder: This uses jQuery.
You could set a class to that background color and then filter by class name $(".classname").
OR
You could add a new selector like explained here:
Is there a style selector in jQuery?
Not necessarily a great idea, but you could add a new Sizzle selector for it:
$.expr[':'].width = function(elem, pos, match) {
return $(elem).width() == parseInt(match[3]);
}
which you could then use like so:
$('div:width(970)')
//That's going to be horrifically slow, though, so you'd want to narrow down on the number >of elements you're comparing with something like :
$('#navbar>div:width(970)')
//to only select those divs that are direct descendants of the navbar, which also have a >width of 970px.

CSS version of target attribute [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there a css-version of the target attribute like , instead of writing
Link
i could have wrote :
<style type="text/css">
a { target:something; }
</style>
No, there isn't.
Firstly, target is an HTML attribute, not a CSS style property. CSS cannot modify or create a new attribute. You can, however, style all a elements that have target attributes with the selector:
a[target] {
...
}
You can't for the moment, but there was a working draft by the W3C called CSS3 Hyperlink Presentation Module, now abandoned. It defines a CSS property named target which is meant to substitute the HTML attribute, and actually is way more specific and allows to do more than the old HTML target. Unfortunately, as fas as I know, no browser tried to implement it, I think that's the cause of abandonment. However, in the future could be proposed again (I hope, at least).
As others have stated - there is not a way to do this with CSS yet.
A way to do this is with jQuery+css.
If you have given all of your links a specific class, use this jQuery to set the target, and if you want to set the target for ALL links, use the second set of code:
$(document).ready(function(){
if($('a').hasClass('CLASSNAME')) {
$(this).attr("target", "TARGET");
}
}
If no class is set and you want all of the links on your page (that aren't internal links) to have a set target, use this:
$(document).ready(function(){
$('a[href^=http]:not([href^=http://YOURSITEURLWITHWWW],[href^=http://YOURSITEURLWITHOUTWWW])')
.add('a[href^=www]:not([href^=YOURSITEURLWITHWWW])')
.attr('target','_blank');
}

.closest() in CSS [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a CSS parent selector?
I am able to hide a DOM tree which look in this way by using .closest().
<div class='parent'>
<!-- some html code -->
<div class='child'>
</div>
<!-- some html code -->
<div>
$('.child').closest('parent').hide();
It will be possible to get the same effect just by using CSS?
If yes, how?
No selector currently exists that can select a previous or parent element.
There is a level 4 selector that is currently being developed.
So in the future, you may be able to do something like this:
!.parent > .child { display: none; }
But until then, you'll have to stick with
$('.child').parent();
in jQuery.
No. See for yourself, no such selector exists in CSS3, and not in CSS2 either.
Might be able to use this
.child:parent .parent{display:none;}
http://css-tricks.com/parent-selectors-in-css/

Change HTML element by ID [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Change an element's CSS class with JavaScript
Found lot of topics about this topic, but none helped me. I have:
<div id="text-6" class="block col-228">
Javascript code should add new class fit, so result should be:
<div id="text-6" class="block col-228 fit">
How to do that with javascript?
Try like this:
var elem = document.getElementById("text-6");
elem.setAttribute("class", elem.getAttribute("class")+" fit");
Important note: You need to be assure,that your DOM Hierarchy is constructed completely,then try to manipulate DOM Elements. That is why you need to put DOM manipulation scripts inside of the window.onload callback, or if you use jQuery, then inside of $(document).ready callback.
You put the following between your script tags.
document.getElementById('text-6').className += " fit";
I'd recommend using jQuery. Then you can just do something like this:
$("#text-6").addClass("fit");
EDIT:
Including the whole jQuery library may be overkill for your situation, but if you're dealing with DOM manipulation a lot, jQuery can simplify things quite a bit. If it's just for this one thing, then some of the other answers provided would be better.

Jquery unwrap() method? [duplicate]

This question already has answers here:
jQuery : remove element except inside element
(4 answers)
Closed 8 years ago.
There is a great method in jquery called wrap() that will wrap a selected element inside a new element, like so:
Start with:
<p>I wish I was wrapped!</p>
Add code:
$("p").wrap("<div></div>");
End with:
<div><p>I wish I was wrapped!</p></div>
But what I need is something that will unwrap, so that the above process is reversed. It seems that the issue is that when you select a bad item (let's say an unnecessary table) that it always grabs what is inside it as well, so if I want to remove all <td>s, I am left with nothing, since that removed the td and anything inside.
Is there a standard reliable way of removing elements but leaving any children/ancestors alone?
In JQuery 1.4 unwrap() was added:
http://api.jquery.com/unwrap/
A quick Google search reveals that there is such functionality, in the form of a small 576 byte plugin called jqueryunwrap. I have not tried it personally, but it is worth a shot. ;)
$("p").unwrap() will unwrap the wrapping div....................I hope this helps

Categories