pure javascript select child dom - javascript

I'm learning not use jquery only pure javascript, just start and have trouble .....
how to select child dom
<div class="row-button">
<input type="submit" />
</div>
I'm trying below code but all shows error message.
var submit_button = document.getElementsByClassName("row-button");
console.log(submit_button.nodeType); //undefined
console.log(submit_button.firstChild); // undefined
console.log(submit_button.childNodes[0]); // TypeError: 'undefined' is not an object (evaluating 'submit_button.childNodes[0]')
or I thought maybe need to add window onload to sure dom ready so
window.onload = function () {
var submit_button = document.getElementsByClassName("row-button");
console.log(submit_button.nodeType); //undefined
console.log(submit_button.firstChild); // undefined
console.log(submit_button.childNodes[0]); // TypeError: 'undefined' is not an object (evaluating 'submit_button.childNodes[0]')
}

Pay attention: it's getElementsByClassName.
This means it returns a NodeList (an array-like object) of matching elements.
Try:
submit_button = document.querySelector(".row-button");
This will not only add support for IE8, but also return a single element, that being the first element with the desired class.

getElementsByClassName("row-button")
returns an array of elements of class "row-button". So to get its first (and only in your code) child, use
var submit_button = document.getElementsByClassName("row-button")[0];

Related

get content of some tags inside a variable

var a = $('#txta').val();
console.log(a);
result is complete html code from this url
Now I want to get content of all #artikal-naziv tags (there are 96)
var b = a.find("#artikal-naziv").text();
console.log(b);
Result:
Uncaught TypeError: a.find is not a function
Any help?
Actually you are calling .find() on a string and not in a DOM element.
Because from $('#txta').val() you are getting a string, that's why you got Uncaught TypeError: a.find is not a function, because string doesn't have .find() method.
You should change it to:
var a = $('#txta');
Then you can write:
var b = a.find("#artikal-naziv").text();
Note:
Now I want to get content of all #artikal-naziv tags (there are 96)
You can't set the same id #artikal-naziv for multiple elements (96), the id should be unique in the page.
Another thing .val() call assumes that your element is a form element, you can't call .val() on a div or a span, if it isn't a form element use .html() instead.
Because "a" is not a jQuery object - it's usually a string containing value of the returned element (txta).
Use $(a).find(...) instead - that will probably do it.
Ref link: https://stackoverflow.com/a/3532381/3704489
As per what I can make out of your description, you are getting HTML as string using var a = $('#txta').val();. If this is true, you will have to create an in-memory element and set this string as its HTML.
Then you will have an in-memory DOM section that you can query on.
You can try something like this:
var html = '<span><p id="artikal-naziv">bla bla</p></span>';
var $tempElement = $('<div>').html(html);
console.log($tempElement.find('#artikal-naziv').text());
// or using vanilla JS
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
console.log(tempElement.querySelector('#artikal-naziv').textContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
.val() takes out the value from the element....Whereas all DOM operations are done on the element... because function like .find() , .hide() , .show() , .closest() etc are used with the element not the value
The Following modifications should work...
var a = $('#txta'); // $("#ID") returns the element
console.log(a.val()); // $("#ID").val() returns the value
the result is complete html code from this URL
Now I want to get content of all #artikal-naziv tags (there are 96)
var b = a.find("#artikal-naziv").text(); // .find() easily works on element
console.log(b);
Simply use .find to find children and .closest to find parents:
<div class='a'>
<div class='b'>
<div class='c'></div>
<div class='c'></div>
<div class='c'></div>
</div>
</div>
js:
var a = $('.b');
a.find('.c'); // Will return all the objects with the class c
a.closest('.a'); // Will return the first parent with the class a

"thing.appendChild is not a function" for object method

Apologies for the horrific title; I'm unsure how to summarise this problem in such few characters.
TL;DR Why doesn't $("#canvas").appendChild() work?
I have a prototype Car which, on instantiation, is supposed to create a div inside a div whose id is "canvas".
$(document).ready(function() {
var canvas = $("#canvas");
function Car(speed) {
...
this.domDiv = document.createElement("div");
$(this.domDiv).addClass("car");
this.addToCanvas = function() {
canvas.appendChild(this.domDiv);
};
this.addToCanvas();
...
}
car1 = new Car(0.5);
});
However, I get Uncaught TypeError: canvas.appendChild is not a function, and I don't understand why.
appendChild is a DOM function. append is a jQuery function (canvas is a jQuery object).
I think the correct function is append, rather than appendChild on a jQuery wrapper
canvas.append(this.domDiv);
You would want to use appendChild if you used a host query selector (document.getElementById('canvas')) rather than a jQuery selector ($('canvas'))

.children().innerHtml on a JQuery object from a DOM node object returns undefined

function getTaskProperties(node) {
var data = {};
data.name = $(node).children(".nameHere").innerHtml;
data.date = $(node).children(".dateHere").innerHtml;
data.class = $(node).children(".classhere").innerHtml;
console.log($(node).children(".nameHere")); // returns something like:
//[p.nameHere, prevObject: n.fn.init[1], context: div#entryTemplate.entry, jquery: "1.11.0", constructor: function, selector: ""…]
console.log($(node).children(".nameHere").innerHtml); //returns undefined
return data; }
function getAllTasks() {
var tasks = [];
$(".entry") .each(function (i, e) {
console.log (getTaskProperties(e));
})
for (var i; i<tasks.length; i++) {
console.log(tasks[i]);
}
}
This script runs through a series of HTML elements that look like the following:
<div class = "entry" id = "entryTemplate">
<a class = "trashButton"><i class="fa fa-trash-o"></i></a>
<p class = "classHere">History</p>
<p class = "dateHere">Due: Monday</p>
<p class = "nameHere">Graphic Organizer</p>
</div>
There are also a couple other elements that get included in the JQuery selector for <.entry>
My problem is that when I run $(node).children().innerHtml it returns undefined.
How can I properly get the value of .classHere, .nameHere, and .dateHere?
.innerHTML is a DOM property name (and you had it with the wrong capitalization).
$(node).children(".nameHere") produces a jQuery object.
.innerHTML is NOT a property of a jQuery object (it's a property of a DOM object) and thus is does not work on a jQuery object.
You can either use all jQuery:
$(node).children(".nameHere").html()
or you can fetch the DOM object from the jQuery object and then use .innerHTML as in:
$(node).children(".nameHere")[0].innerHTML
By way of explanation - a jQuery object and a DOM object are not the same thing. They are different types of objects that have different properties and methods.
A jQuery object contains an array of DOM objects (inside it). So, when you want to carry out an operation on the DOM objects, you can either use a jQuery method which will apply that method to the DOM objects inside the jQuery object or you can fetch the DOM objects out of the jQuery object and apply DOM methods/properties directly to the DOM objects.
Use .html() or .text()
$(node).children(".nameHere").html();
$(node).children(".nameHere") is jQuery Object you cannot directly use .innerHTML with it
You can do
$(node).children(".nameHere")[0].innerHTML;
or .get()
$(node).children(".nameHere").get(0).innerHTML;

Value is undefined when element is obtained with jQuery

Below is the code where I obtain my input element with jQuery:
var txt = $(tableRow).find('input:text');
if (txt.value == null) {
//TO DO code
}
and here's how I do it with pure JavaScript
var txt = document.getElementById('txtAge');
if (txt.value == null) {
//TO DO code
}
With the first way the value of the txt is undefined. But with the second way the value is what's inside the input element. Now more interesting is, on the bottom-right pane of the Mozilla Firebug if I scroll down to the "value" of the txt I can see it there, both ways.
I know I can simply say $(txt).val(), but I also want to understand why I can't access the value of an element if it's been selected by jQuery. Isn't jQuery just a library of JavaScript functions?
.value is not part of the jquery api. You should use .val() instead:
var txt = $(tableRow).find('input:text');
if (txt.val() == "") {
//TO DO code
}
A dom object and a jquery dom object are not exactly the same. In fact, you can open the Developer tools (in webkit) or Firebug (Firefox) to check what are they in the inside. Jquery holds more information (actually, it contains an instance of the dom that it's representing). So, if you wanted to use .value, you need to call the "generic" dom object from the jquery object, and then use .value.
jQuery selects DOM elements using various native and non-native techniques and places them all in it’s own array-like instance that also wraps them in their own API. jQuery doesn’t "extend" native DOM properties or methods, so you will need to target the DOM node to do that.
Think of it like this:
var node = document.getElementById('txtAge'); // the DOM node
var txt = $('#txtAge'); // the same node wrapped in a jQuery object/API
Since jQuery object holds an array-like collection of DOM nodes, so you can access the first element by doing:
txt[0] // same as node
But it’s generally recommended that you use the .get() method:
txt.get(0)
Another more jQuery-way to do what you want is to iterate through a jQuery collection using .each():
$(tableRow).find('input:text').each(function() {
// "this" in the each callback is the DOM node
if ( this.value == null ) {
// Do something
}
});
.find() will return an arry-like object. If you're sure that there's one, and one only, element matching your query, you could do
var txt = $(tableRow).find('input:text')[0].value;
That's not very jQuery-like, so to speak, more like a mismatch of both jQuery and DOM methods, but it'll get what you want. Also, since you show, as a DOM example, var txt = document.getElementById('txtAge');, this could be rewritten in jQuery as
var txt = $('#txtAge')[0];
var x = $(tableRow).find('input:text');
It's an jquery object .
`x.value`
There is no property value in jquery object . So it returns undefined.
x.val() is a method you can use for get the value of an element.

Retrieving an element by array index in jQuery vs the each() function

I was writing a "pluginable" function when I noticed the following behavior (tested in FF 3.5.9 with Firebug 1.5.3).
$.fn.computerMove = function () {
var board = $(this);
var emptySquares = board.find('div.clickable');
var randPosition = Math.floor(Math.random() * emptySquares.length);
emptySquares.each(function (index) {
if (index === randPosition) {
// logs a jQuery object
console.log($(this));
}
});
target = emptySquares[randPosition];
// logs a non-jQuery object
console.log(target);
// throws error: attr() not a function for target
board.placeMark({'position' : target.attr('id')});
}
I noticed the problem when the script threw an error at target.attr('id') (attr not a function). When I checked the log, I noticed that the output (in Firebug) for target was:
<div style="width: 97px; height: 97px;" class="square clickable" id="8"></div>
If I output $(target), or $(this) from the each() function, I get a nice jQuery object:
[ div#8.square ]
Now here comes my question: why does this happen, considering that find() seems to return an array of jQuery objects? Why do I have to do $() to target all over again?
[div#0.square, div#1.square, div#2.square, div#3.square, div#4.square, div#5.square, div#6.square, div#7.square, div#8.square]
Just a curiosity :).
.find() returns not an array of jQuery objects, but one jQuery object containing an array of DOM elements (a jQuery object, at it's core, is a wrapper around a DOM element array).
When you're iterating through, each element you're on is a DOM element. So, it needs to be wrapped in $(this) to become jQuery object and have access to those methods.
Also as a side note: The id attribute can't begin with a number, since it's invalid HTML you may or may not experience strange behavior, especially cross-browser (this rule applies for any invalid HTML).
No, the find method doesn't return an array of jQuery objects. You are creating a jQuery object for each element here:
console.log($(this));
If you log the value without creating a jQuery object from it:
console.log(this);
you will see that it's an element, not a jQuery object.
When you access the jQuery object as an array, you get an element. If you want a jQuery object you have to create one from the element.

Categories

Resources