Javascript - Select element by id name [duplicate] - javascript

This question already has answers here:
What is the difference between getElementById and simply using an element's ID as a variable?
(2 answers)
Closed last year.
Normally I select elements with an id via document.getElementById('idName'). But apparently you can also select them by name only 'idName'. I was not aware of this until recently. I wanted to know if this is a "bad practice" to select elements by their idName? I have already used the search engine and found nothing about select by id name. So here is my question now.
console.log(idName)
<div id="idName">Hello World</div>

I believe this is a bad practice because you can get yourself confused and cause conflicts with your own js variables.

I can't say it's Good or bad But
you should be very careful while using . This can cause many problems So I will recommend use in Small Projects only .
(it's My personal recommendation )
Suppose Your JavaScript loads First then it will throw an error and none of the code will work
For more Information
just typing in 'idName' isn’t a “short form” of document.getElementById() It’s a reference to a global variable

Related

jQuery, which is best, assigning element to variable or not? [duplicate]

This question already has answers here:
Is storing jQuery elements in variables more efficient?
(5 answers)
Closed 2 years ago.
While reading jQuery and Bootstrap documentation I often see this:
var modal = $('#someid');
modal.find('.something').text('something');
modal.find('.somethingelse').text('somethingelse');
It first assigns the element to a variable, then works from there. However I usually write this:
$('#someid').find('.something').text('something');
$('#someid').find('.somethingelse').text('somethingelse');
My question is, are there reasons for using the first method - assigning to a variable - other than the syntax itself? Is it faster or better regarding the DOM?
The first method is preferred for multiple reasons.
It cuts down on the number of times the DOM has to be accessed, which is a relatively slow operation and so it performs better.
It reduces the number of times your code instantiates a new jQuery object from an existing Element object, which is another performance benefit.
It DRYs up the code so that the same statements are not needlessly repeated.
As such you should always follow this practice, known colloquially as 'caching the selector', where possible.

Access HTML elements based on id identifier [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 9 years ago.
I was playing with javascript, and I don't understand how this little snippet can works:
html > <div id="foo_bar"></div>
javascript > foo_bar.textContent = "Hello, world!";
result > <div id="foo_bar">Hello, world!</div>
foo_bar is not a variable defined before in the code. I only have this one line in my javascript code.
Check the jsFiddle demo : http://jsfiddle.net/6W25e/
So what really happend?
I always thought that was impossible to access dom elements without dom methods like element.getElementById().
Is there any documentation on this behavior? (my searches have been unsuccessful on mdn)
Taken from bobInce
What is supposed to happen is that ‘named elements’ are added as apparent properties of the document object. This is a really bad idea, as it allows element names to clash with real properties of document.
IE made the situation worse by also adding named elements as properties of the window object. This is doubly bad in that now you have to avoid naming your elements after any member of either the document or the window object you (or any other library code in your project) might want to use.
Read more: Do DOM tree elements with ids become global variables?
This means it's very bad practice to do that, and some browsers don't support it, the good ones that don't fall into the trick.
What happens is that some browsers will make them global variables as classes of window, making them immediately accessible when the window loads.

Is getElementById optional in some browsers? [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
When accessing elements by window.someThing, the "someThing" should be the name of html element. But what I see now, is that I can access an element by id in the same way, without document.getElementById. When has this been changed? It looks like it works in Chrome, IE, Firefox 13, but not in Firefox 12.
For example:
<div id="MyDiv">Content</div>
<script>
MyDiv.innerHTML = "New Content";
</script>
Why does the example above work? Why don't I have to do:
var MyDiv = document.getElementById('MyDiv');
Is it something new, or has it always been possible and I just didn't know it?
http://www.quirksmode.org/dom/w3c_core.html#gettingelements
It's been (mostly) implemented since IE 5.5
I can't really find any info on using the ID as variable name. I'd suggest on sticking to getElementById("MyDiv").doSomething instead of MyDiv.doSomething, to improve compatibility.
Especially when you're writing larger scripts, you may mix up variable names with id's used in the page. getElementById ensures you "get" the DOM element.
This is not standard behavior in JavaScript. When adding a variable as you did with var MyDiv, the variable was added to the window object so that it could be accessed directly as if it were a property, but DOM elements were never added. I don't personally know the reasons for the new behavior, but my guess would be that it's just an expansion of the language engine's capability. If you really want to know what the behavior is supposed to be, you could always read the standard: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Edit: Also, note that the method that is used to get the element is document.getElementById() which comes from the document object model. The method you're referring to is placing an id into the window object which can create conflicts by id. The standard defined method is to get the element from document and avoid putting things into the window. Using the window object in this manner would be similar to using a global variable (which is a bad practice re: http://www.javascripttoolbox.com/bestpractices/#namespace)
You can find your answer here: Can I Use an ID as a Variable Name?
In short, avoid it.
The reason it works is because the browser actually creates a variable window.document.myDiv
AVOID IT!
It seems like an amazing feature but I would recommend not using it because if you have divs with id same as that of some global JS variables, it would be conflicting and will also mess-up stuff in some other third party JS files that you include.
But You always have jQuery selectors always with you and not to forget the new querySelector feature in modern browsers :)

Is it OK to add your own attributes to HTML elements? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Custom attributes - Yay or nay?
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
In current learning project I am working on, I need to add an attribute whose value will be a number. At first I thought of using "id" for this purpose but an answer revealed that it is not good to do that.
Is it OK if I create my own attribute, say "messid" and assign a numeric value such as "12", "6" etc to it?
Here is why I want to do this so that you can correct me if I am doing it totally wrong:
I need to access this number in my JavaScript (using jQuery). Just taking the value of attribute is easy but extracting the numeric value from a string like "m12" or "m6" is a pain. (I am a beginner in JavaScript world.)
There has been much discussion about this:
Custom attributes - Yay or nay?
How to store arbitrary data for some HTML tags
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
At the end of the day, I am on the camp that believes data attributes are the best way to go. They are being introducted in HTML5 to avoid name conflicts. Essentially, if you want to store anything data related you just prepend "data-" on the attribute name:
<div class="user" data-userid="5"></div>
The only con to the whole thing is then that your XHTML won't validate, but I honestly don't care about that stuff. (That's right, I said it)
In HTML 5 you're allowed to add any attribute starting with data-, so e.g. <div data-messid="12"> is OK.
HTML 4 and XHTML 1 won't validate if you add your own attribute, but besides that nothing bad will happen if you choose attribute name unique enough (so it won't conflict with any current or future HTML attribute).
Just so you know, you can easily extract an ID from a string like m12 or m6, I would do it like this:
//name the IDs m_12, m_3 etc
var number = $('#someElement').attr('id').split('_')[1];
Or if say, you have a bunch of links with numbers in the ID as above, and all the links have the clickMe class:
$('a.clickMe').click(function() {
alert($(this).attr('id').split('_')[1]);
});
I use custom attributes, and since they are supported by all browsers I checked I think it is not bad to use them. You can also use custom HTML tags to simulate HTML5, with some IE hack, so why not use attributes, if they don't need any hacks?
Anyway, you can read similar discussion here:
Custom attributes - Yea or nay?
This isn't a definitive answer, but having had to do this in the past I can say this not only works well, it is cross-browser friendly.
If using jQuery you can use .data to store custom information against an element.
The downside of custom attributes are:
IE6 creates extra objects to store custom 'expando' attributes these have a tendency to leak especially if they are created via script.
validation issues
No - it's not.

How can i trace changes made to the DOM by JavaScript? [duplicate]

This question already has answers here:
DOM attribute change debugging
(4 answers)
Closed 9 years ago.
I have a large website in development with a large amount of JS in different files. I have come across an issue where something is removing a class from the DOM. I can see it when I view source but not in Firebug.
Normally I would place some alerts/console.log calls with the hasClass value but because I have no idea where to start I wanted to know if I can trace the change back when it occurs somehow?
Denis
Firebug lets you set a breakpoint and single-step through your code. This should make it clear where the issue is happening.
that specific class name must be in use in that hidden function that remove it, right?
so either grep for it on posix-based system, or, if you are using Win system, use your IDE "search-in-files" function to trace that modification.

Categories