This question already has answers here:
jQuery select by class VS select by attribute
(2 answers)
Closed 6 years ago.
If you have html and throughout you have span elements like this:
<span id="element-1" class="elements"></span>
<span id="element-2" class="elements"></span>
<span id="element-3" class="elements"></span>
What is faster to find them:
$('.elements')
or
$('[id^="element-"]')
I don't think speed is a concern here, the difference between them is so quick it wont effect your code..
I think, id selector works faster.
HTML ID attributes are unique in every page and even older browsers can locate a single element very quickly.
Id is obviously faster then class because there can be only one Id, once found need no more search. However the speed is not concern. If you need to do some work on multiple elements you use class but if you need to do work on a particular element you use Id.
Id's in html are auto assigned in JS.
Because there can be only 1 id on the page with that name. the entire element is assigned into a JS variable.
For example: the element <span id='spanTagOne'>Text</span> will be a JS variable spanTagOne.
So you don't even need to get them since they are already assigned.
try this way to find
$('parent').find('.child') is a faster way to find element.
For some reason I can't access HTML element's display style's value.
Here's my JavaScript code:
var el = document.querySelector('#warning');
console.log(el.style.display)
My code returns "" empty string for #warning's displaystyle but it's actually "none".
I've the following HTML:
<div id="warning">
warning warning warning.
</div>
I've the following CSS:
#warning {
display: none;
}
Any ideas?
You are doing everything right for the most part, but what you are running into is a hangup for most people when they try this for the first time.
The style object in javascript is looking for this value to be inside the actual element (inline) and does not look for it in css code directly.
To access the style, the style has to exist in the dom. You could look into Window.getComputedStyle()
I hope this explains why you are reaching this roadblock.
If you know the element is an ID I'd suggest you use the getElementById(); function. Also AFAIK the style method gets inline styles only. I'd suggest using getComputedStyle();.
Code
var myDiv = document.getElementById("myDiv");
alert(getComputedStyle(myDiv).display);
Will output "none".
Example
http://jsfiddle.net/43jLLd5L/
Reading Material
Not directly related to your question but the answer has some good points.
I am able to easily change the style or the tag of an element based on certain criteria using JavaScript:
document.getElementsByTagName("mainclass")[0].style.color:#ffffff;
However, is there a way to do this is the style contains multiple classes and a tag like so
.mainclass .secondaryclass div td {
color: #000000;
}
The following is not working for me so im sure there is a totally different way of doing it:
document.getElementsByTagName(".mainclass .secondaryclass div td")[0].style.color:#ffffff;
...
The other option if easier is to figure out how to use JS to embbed a external style sheet (and not at the end of head, just where the JS code is thats where the CSS should go)
Thanks!
getElementsByTagName does not accept CSS selector syntax. You're looking for querySelectorAll but you'll have to iterate over the returned list to assign the style, and it's not completely supported across browsers.
...which is why everyone uses jQuery.
Example, assuming you want to modify just the first matched element:
document.querySelectorAll(".mainclass .secondaryclass div td")[0].style.color = '#ffffff';
Note the change from : to =, and wrapping the color value in quotes. JavaScript has different syntax from CSS; I suggest that you take some time to learn it.
This question already has answers here:
How do I check if an element is hidden in jQuery?
(65 answers)
Closed 8 years ago.
Using .fadeIn() and .fadeOut(), I have been hiding/showing an element on my page, but with two buttons, one for hide and one for show. I now want to have one button to toggle both.
My HTML / JavaScript as it is:
<a onclick="showTestElement()">Show</a>
<a onclick="hideTestElement()">Hide</a>
function showTestElement() {
$('#testElement').fadeIn('fast');
}
function hideTestElement() {
$('#testElement').fadeOut('fast');
}
My HTML / JavaScript as I would like to have it:
<a onclick="toggleTestElement()">Show/Hide</a>
function toggleTestElement() {
if (document.getElementById('testElement').***IS_VISIBLE***) {
$('#testElement').fadeOut('fast');
} else {
$('#testElement').fadeIn('fast');
}
}
How do I detect if the element is visible or not?
You're looking for:
.is(':visible')
Although you should probably change your selector to use jQuery considering you're using it in other places anyway:
if($('#testElement').is(':visible')) {
// Code
}
It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).
jQuery 3
:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):
Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!
Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.
Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():
function toggleTestElement() {
$('#testElement').fadeToggle('fast');
}
There's no need, just use fadeToggle() on the element:
$('#testElement').fadeToggle('fast');
Here's a demo.
if($('#testElement').is(':visible')){
//what you want to do when is visible
}
I know, that two elements can't hav the same id. But it's happens so, that in my project I have two elements with same id in other divs, like this
<div id="div1">
<img id="loading" />
</div>
<div id="div2">
<img id="loading" />
</div>
And CSS:
#div1 #loading
{
some style here...
}
#div2 #loading
{
another style here...
}
Works fine for me, but maybe it is not reccomended to do by so?
Yes, I know, thet I can use classes, and it's strongly recomended to do by so, but I want to know is there any potential risk in this usage of id?
I think no, because when I wrote for example
$("#div1 #loading")... it becomes a unique element.
Isn't it?
Change your id to class. It is not a good idea to give duplicate id.
Think two students having same roll no in a class. Imagine them getting examination result. How will the school be able to recognise the marksheet?
Your way is not cross browser compatible, and will affect a lot while coding JavaScript, and posted form etc
You can get the same effect using class
see
<div id="div1">
<img class="loading" />
</div>
<div id="div2">
<img class="loading" />
</div>
and css:
#div1 .loading
{
some style here...
}
#div2 .loading
{
another style here...
}
an id must (should) be unique!!
you will have troubles selecting it via JS in most browsers -
better use class
The big reason is for JavaScript DOM manipulation. In your case, if you do something like this...
document.getElementById("loading")
... JavaScript will return the first element, and the first element only. You'll have no way to access the rest of them without some serious DOM walking.
Just because no-one else has posted it - the HTML spec, section on ID, which says:
id = name [CS]
This attribute assigns
a name to an element. This name must
be unique in a document.
Yes you are right, it is not recommened to do so. An ID should always be unique (e.g. if you want to select the element with javascript).
If you just want to add the same style to the divs, just use css class.
Unique:
In mathematics and logic, the phrase "there is one and only one" is used to indicate that exactly one object with a certain property exists.
#div1 #loading does not remedy the fact that you have two instances of #loading in your document. So, no, don't do that.
IDs should be unique, so id1 and id2 are fine, but for many elements with the same style, use an HTML class and CSS class selector:
.loading
{
styles here
}
These are allowed to be repeated as many times as you want on a page :)
Is it normal? No.
Is it recommended? Definitely not! It's actually prohibited (but enforcement is weak).
But it (apparently) works, so ...
Id are used to distinguish elements, they must be unique for different reason, one of them is the use of javascript, function like getElementById won't work well if you have duplicate ID, you won't be able to predict what it'll do on different browser as JS is self-implemented on each browser differently.
If you wish to use a structure like #div loading and #div2 loading it seem clear that both loading have similar uses so they should be classes and would be used like this
#div1.loading and #div2.loading
Also one plus of using this syntax would be to put the common style in .loading like this
.loading{ style common to both the loading }
#div1.loading{ style used only by the loading in div1 }
#div2.loading{ style used only by the loading in div2 }
https://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id
BUT!
If you need it in your project, you can use it, like suggested in my Question Final Update!
validation and purist-ism aside, it is perfectly functional. But I would definitely be annoyed if I use that #loading id and find that a jquery effect or a css effect applies to more than 1 element.Do tell me if IE6 or 7 or Firefox 1.x or 2.x ruins that code.
It's bad practice of using I'd on element. Because I'd giving something for understanding unique with their name identification. And second thing we use its in CSS but in JavaScript this bad practice. So good example for this class and student.
So don't do this.
I disagree on people saying to always use a "unique", meaning different ID everytime you label one. Sometimes its acceptable, such as my case where I am making a calculator.
The javascript is doing the math and outputting the result into the div with the id="total". I need that same exact "total" to be in 2 different places however. In this case, why wouldn't I use two different div's with the same ID? I need the same number in both boxes. With jQuery, I perform and output the math once and it populates both div's at the same time, which is what I want.
So long as you understand the risks where if you were PULLING information from those 2 div's with the same ID, then I say feel free. As long as you dont confuse yourself and need 2 different results in the same div ID.