Getting a single element with `getElementsByTagName` - javascript

I know that if we want to find a group of elements, getElementsByTagName is the method for us and it returns a NodeList. but if we are looking for tag name with "body" , then why we need to add [0] after the ("body") element? There is only one body tag in an HTML document.
var body = document.getElementsByTagName("body")[0];
body.className = "unreadable";
why we cant write this code without index[0] like this
var body = document.getElementsByTagName("body");
body.className = "unreadable";
If i write this code the class unreadable will not be added with body tag ...why?

Because document.getElementsByTagName allways returns NodeList. If you want find easier way to retrieve body you can use just document.body

getElementsByTagName returns a NodeList. It might have no items in it. It might have one. It might have many. You can see how many are in it by testing its .length.
It would be confusing if it sometimes returned a NodeList and sometimes returned an ElementNode.

getElementsByTagName [docs] always returns a NodeList. It does not matter whether an element with a certain tag exists only once.
It would be bad if the function behaved inconsistently.

Related

Why is innerHTML returning 'undefined'?

I'm trying to catch the "value" inside this div, which is editable:
<div class="editable-div" contentEditable="true">Hey</div>
I figured I could do this simply via JavaScript:
var changedText = $('.editable-div').innerHtml
However, this variable will always return "undefined", which confuses me.
Can someone enlighten me on how to reach this "value"?
It is jQuery - you have to use:
$('.editable-div').html()
A jQuery wrapped object is actually not the raw DOM node, but essentially an array of raw DOM nodes that can be acted upon with jQuery specific methods, such as .html(). If you want to interact with the DOM node, you can retrieve it by either iterating through the list or getting the element of that list if you know which one it is:
$('div').each(function(index, element) {
element.innerHTML // ...
}
$('div').get(0).innerHTML
$('div')[0].innerHTML
Note that while it is "kind of" like an array, in that you can get DOM nodes using the array syntax of $('div')[0], you can't treat it like an array in Javascript. In other words, you can't do this:
$('div').forEach(function(element) {
element.innerHTML
}
innerHtml is used with javascript selector and you are using jQuery. so replace innerHtml with .html() or .text() function.
Use this:
var changedText = $('.editable-div').html();
innerHtml is DOM. try $('.editable-div')[0].innerHtml

JQuery doesn't reads dynamic created element attributes

Well, I think this gonna be a simple question, but I'm unable to realize how Jquery loses/is not able to find attributes of the element:
Javascript:
for (var i=0; i<=10; i++)
{
Cells[i]=document.createElement('div');
Cells[i].id = "Cell"+String(i);
Cells[i].className = "CellClass";
if (i==0)//Let's look the fist one (neverminds which one).
{
alert(Cells[0].className);//This would alert: "CellClass" (without quotes).
alert($("#Cell0").className);//This would alert: "undefined" (without quotes).
//Another way:
alert($(Cells[0]).className);//This would alert: "undefined" (without quotes).
}
}
for the question, class .CellClass is not relevant itself, neverminds which attributes define.
What am I not understanding?
$(Cells[0]) returns a jQuery wrapper object not a dom element reference so it does not have properties like className.
You can use any one of the following method
Cells[0].className
$(Cells[0]).prop('className')
$(Cells[0]).attr('class')
Also make sure that the element is added to the dom structure before the jQuery selector $("#Cell0") is executed else the element will not be found in the dom lookup
Not withstanding Arun's answer about the difference between jQuery objects and DOM objects, you'll also find that $("#Cell0") won't actually work until #Cell0 has actually been placed in the DOM, by adding it to a parent node.
alert($("#Cell0").attr('class'));
Will work

Javascript: Remove Child when using document.write

I want to have something like this:
var abc1 = document.write('<html>HTMLPAGECONTENTHERE</html>');
function removepage(){
abc1.parentNode.removeChild(abc1);
}
removepage();
That won't work; document.write doesn't return anything.
You should use the DOM APIs instead (createElement() and appendChild()), or, more easily, jQuery.
document.write inserts a stream of HTML directly into the page. It has no useful return value.
If you want to manipulate what it outputs via DOM, then you have to have a known quantity to match with getElementById, getElementsByTagName or some other method for getting HTML Element Nodes from a DOM.

JQuery select by ID vs document.GetElementByID

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?
Thanks!
// works
addTask(document.getElementById('taskText'), evt);
// doesn't
addTask($('#taskText'), evt);
getElementById() returns a DOM element reference.
jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using
$('#taskText').get(0);
See http://api.jquery.com/get/
To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:
addTask($('#taskText')[0], evt);
$('#taskText') returns a jQuery object reference.
document.getElementById('taskText') returns a DOM element reference.
If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.
If you want to get the first DOM element reference from the jQuery object, you can do so with this:
$('#taskText').get(0)
So these two should be identical:
$('#taskText').get(0)
document.getElementById('taskText')
Both are not exactly same
document.getElementById('taskText'); //returns a HTML DOM Object
var contents = $('#taskText'); //returns a jQuery Object
var contents = $('#taskText')[0]; //returns a HTML DOM Object
so you have to change it to get HTML Dom Object
addTask($('#taskText')[0], evt);
As #Phil and #jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.
Think of it as a zero based array, you could pass in the DOM element by doing this:
addTask($('#taskText')[0], evt);

problem with javascript getElementById that is hidden

I am trying to make a bookmarklet that will return a user id for a website i am registered for. When logged into the website there is a piece of code as follows:
<input id="memberID" name="00V85345345343ugFFC" type="hidden" value="3959721"/>
This is the JavaScript i am using but it doesnt do anything. AmI doing something wrong here?
javascript:alert("Your member ID is\n"+document.getElementById("memberID")[0].value);
document.getElementById returns a HTMLElement or null if no element was found matching that ID.
Because element ID's are supposed to be unique, it makes no sense to return an Array; a maximum of one element should be matched.
javascript:alert("Your member ID is\n"+document.getElementById("memberID").value);
document.getElementsByTagName however, for example (note the plural of elements, rather than element), returns an array of elements; as it makes perfect sense to have more than one element of the same tag in a page.
var divElements = document.getElementsByTagName("div");
if (divElements.length) {
var firstElement = divElements[0];
};
getElementById returns single element, not array of elements.
So this:
getElementById("memberID")[0].value
Must become just:
getElementById("memberID").value
Maby this will help abit in cleaning up that error:
http://p-xr.com/jquery-like-getelementbyid-in-1-line-of-code/

Categories

Resources