Bracket notation dosent work for document.querySelector - javascript

I want to remove the third div element inside the body of the page by setting its style to display:none; and using querySelector with a bracket notation to get the element, but my code returns a error
"TypeError: el is undefined"
and when I try to console.log("el") it returns undefined
I've tried using let, const except of var and some other things
var el = document.querySelector("div")[3]
el.style.display = "none"
It should remove the third div in the page.

You're facing two issues:
The querySelector() method is for accessing a single DOM node. If you intend on working with more than one element, you can use document.querySelectorAll() method which returns a node list
The other issue is to remember that arrays use zero based numbering, meaning [3] accesses the fourth element, not the third. The count starts at zero.
With these two points in mind, what you're looking for is:
var el = document.querySelectorAll("div")[2]; // for the third div
el.style.display = "none";

I'm just going to summarise #Sirko and #CoreyOgburn comments:
Don't use document.querySelector, it returns a single node, instead, use document.getElementsbyTagName (my suggestion) or stick with document.querySelectorAll("div"), which returns an Array of all div nodes on the site. Alternatively, use JQuery. And also, if you want to get the third element, you have to type document.querySelectorAll("div")[2], not [3].

Related

Uncaught TypeError: Cannot read property 'style' of null at HTMLUListElement.<anonymous> [duplicate]

How do I get only one DOM element by class name? I am guessing that the syntax of getting elements by class name is getElementsByClassName, but I am not sure how many elements it's going to return.
document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array-like HTMLCollection returned.
var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];
Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.
// HTML
<div id="myElement"></div>
// JS
var requiredElement = document.getElementById('myElement');
Clarifications :
getElementsByClassName returns a Node List and not an array
You do not need jQuery
What you were looking for was probably document.querySelector :
How do I get only one DOM element by class name?
var firstElementWithClass = document.querySelector('.myclass');
Also see: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector
You can use jQuery:
$('.className').eq(index)
Or you can use the javascript built-in method:
var elements = document.getElementsByClassName('className');
This returns a nodeList of elements that you can iterate and make what you want.
If you want only one, you can access the elements in the javascript version like this:
elements[index]
To anyone looking for a one liner
var first = document.getElementsByClassName('test')[0];
Use NodeList.item().
For example:
var first = getElementsByClassName('test').item(0);
You can try with this:
document.getElementsByClassName("className")[index]

Why is [0] needed for getElementsByClassName to work when there's only one class to select?

I tried using let modal = document.getElementsByClassName('modal') to select an element with the class modal. It only worked after using node selection to select the first result: let modal = document.getElementsByClassName('modal')[0]. I know the method Document.getElementsByClassName() returns child elements which have all of the given class names, but there's only one element in my HTML with that class. I confirmed this in my browser's dev tools by using var x = document.getElementsByClassName('modal').length and logging the value of x to the console (it returned 1 as expected).
Could someone explain why node selection is needed in this case?
Edit: My question is different than the one marked as a duplicate. In that question, they are asking the difference between methods than return a single element and those that return an array-like collection of elements. I'm already aware getElementsByClassName returns an array-like collection of elements, whereas the other methods return one element. My question is why do you need to specify the index in a case where all elements of a class are returned but there's only one element with a class (so one item, the correct item, is returned).
document.getElementsByClassName will return a list of elements with the given class name. Even if there is only one element with that class name it will be in a Node List which is why you have to use the [0]
It is needed because getElementsByClassName Returns an HTMLCollection and not a single element.
To get the item without using [0], use a query selector instead, this will give you the item instead of a collection of items.
let modal = document.querySelector('.modal')
console.log(modal)
document.getElementsByClassName
will return array of element who has this class

TypeError getElementsByTagName is not a function issue

I'm having trouble getting to the source of this problem. Basically the error message I am getting in my console is:
TypeError: $(...).getElementsByTagName is not a function
When I click through to the line it is occuring on it is here:
var inputs = $('directoryresults').getElementsByTagName('input');
I'm not sure why this is happening as I have included jQuery in the header of the page itself:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
Does anyone have any ideas what might be causing this?
Does anyone have any ideas what might be causing this?
The object returned by the jQuery constructor doesn't have the .getElementsByTagName() method.
$('selector') returns a jQuery object. .getElementsByTagName() is a native JavaScript method of DOM elements.
To look for elements with a certain tagname using the jQuery object you currently have:
var inputs = $('directoryresults input');
// OR
var inputs = $('directoryresults').find('input');
To get a like-for-like node list that .getElementsByTagName() would return (note this isn't exactly the same, this will return an array where .getElementsByTagName() will return a HTMLCollection):
var inputs = $('directoryresults input').get();
Note: directoryresults, I am assuming, is either a class or id of a DOM element. Either way you'll want to amend the selector above
getElementsByTagName is a method you will find on Element and Document objects.
$('directoryresults') will return a jQuery object (containing any <directoryresult> elements … so nothing if you are working on an HTML document).
to use getElementsByTagName, you need to extract the elements from the jQuery object:
$('directoryresults')[0].getElementsByTagName
The above will only get the first element from the jQuery object (and it assumes that there will be at least one element) so you should probably replace the hard coded [0] with a for loop.
That said, you should generally use the find method instead:
$('directoryresults').find('input')
… or just use a descendant combinator in the first place:
$('directoryresults input')
As noted earlier, directoryresults won't find anything in a valid HTML document. You probably want to prefix it with . or # depending on what you are actually trying to match.
You are ussing a DOM API mixed with jQuery API sintax:
it's document.getElementsByTagName('input');
The first error is not specific if directoryresults is a class or an ID
Nor do you tell if a target item or the item you wish to call
If you use jQuery by TagName type this:
var inputs = $('input');
if you want put values in a div
$.each(inputs, function(){
$('div').append( $(this).val() );
});

can I use document.prototype.getElementById to get an element in another element, not in the whole document

I recently found on this javascript tip :
element_number = Array.prototype.indexOf.call(element_1, element_2);
It allows developers to use the indexOf method on an object wich is not an Array.
I would like to know if it is possible to use a similar syntax to call the getElementById method but not on the whole document (document.getElementById), just on an element like this :
my_div_2 = document.prototype.getElementById.call(div_1, "id_of_my_div_2");
The idea is that my document contains tabs and elements having the same id can be present several times in the document.
If it is not possible, did somebody write a function doing that :
Search in an element another element by id.
No, but you can accomplish what you want using querySelector instead.
my_div_2 = div_1.querySelector("#id_of_my_div_2");
Not supported in IE6/7.
Docs: MDN element.querySelector()
That said, duplicate IDs are invalid.
This technique is useful if the same script is used on different pages where the ID may or may not be in a particular container.
No. The getElementById method must be applied on objects of type Document, otherwise it would throw a WRONG_THIS_VALUE exception. You could try it with
myDiv1 = document.getElementById("div1");
myDiv2 = document.getElementById.call(myDiv1, "div2"); // no ".prototype"!
This makes no sense as only one element with a given id is possible in a document.
So the only right syntax would be
my_div_2 = document.getElementById("id_of_my_div_2");
Don't reuse an id in a document. You probably can achieve the desired result using classes instead of id.

document.getElementById vs jQuery $()

Is this:
var contents = document.getElementById('contents');
The same as this:
var contents = $('#contents');
Given that jQuery is loaded?
Not exactly!!
document.getElementById('contents'); //returns a HTML DOM Object
var contents = $('#contents'); //returns a jQuery Object
In jQuery, to get the same result as document.getElementById, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).
var contents = $('#contents')[0]; //returns a HTML DOM Object
No.
Calling document.getElementById('id') will return a raw DOM object.
Calling $('#id') will return a jQuery object that wraps the DOM object and provides jQuery methods.
Thus, you can only call jQuery methods like css() or animate() on the $() call.
You can also write $(document.getElementById('id')), which will return a jQuery object and is equivalent to $('#id').
You can get the underlying DOM object from a jQuery object by writing $('#id')[0].
Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.
The equivalent would be this
var contents = $('#contents').get(0);
or this
var contents = $('#contents')[0];
These will pull the element out of the jQuery object.
A note on the difference in speed. Attach the following snipet to an onclick call:
function myfunc()
{
var timer = new Date();
for(var i = 0; i < 10000; i++)
{
//document.getElementById('myID');
$('#myID')[0];
}
console.log('timer: ' + (new Date() - timer));
}
Alternate commenting one out and then comment the other out. In my tests,
document.getElementbyId averaged about 35ms (fluctuating from 25ms up to 52ms on about 15 runs)
On the other hand, the
jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs).
From this simple test you can see that the jQuery took about 6 times as long.
Of course, that is over 10000 iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate and .fadeTo. But yes, technically getElementById is quite a bit faster.
No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contents was matched.
The DOM element returned by document.getElementById('contents') allows you to do things such as change the .innerHTML (or .value) etc, however you'll need to use jQuery methods on the jQuery Object.
var contents = $('#contents').get(0);
Is more equivilent, however if no element with the id of contents is matched, document.getElementById('contents') will return null, but $('#contents').get(0) will return undefined.
One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned. However you will get errors if you try to perform operations on the null returned by document.getElementById
No, actually the same result would be:
$('#contents')[0]
jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.
Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection
When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object
In case someone else hits this... Here's another difference:
If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.
This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:
var contents = document.getElementById('a/b/c');
was able to find my element but:
var contents = $('#a/b/c');
did not.
Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:
var contents = $('.myclass[name='a/b/c']);
var contents = document.getElementById('contents');
var contents = $('#contents');
The code snippets are not the same. first one returns a Element object (source).
The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById() for efficiency.
In both the cases if more than one element found only the first element will be returned.
When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.
One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.
Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.
<body id="content">
<h1>Header!</h1>
<form>
<div id="content"> My Form </div>
</form>
</body>
It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.
All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it
<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>
Online Demo!
- https://codepen.io/frank-dspeed/pen/mdywbre
jQuery is built over JavaScript. This means that it's just javascript anyway.
document.getElementById()
The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.
Jquery $()
Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.
All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :
I have an HTML :
<div id="contents"></div>
Go to console (cntrl+shift+c) and use these commands to see your result clearly
document.getElementById('contents')
>>> div#contents
$('#contents')
>>> [div#contents,
context: document,
selector: "#contents",
jquery: "1.10.1",
constructor: function,
init: function …]
As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:
$('#contents')[0]
>>> div#contents

Categories