Javascript building element reference node list - javascript

How can i build a nodelist, which is reference to the selected node?
Example document.querySelectorAll('tr') returns a nodelist contains all the tr element node references on page.
I`m writing methods, to return element nodelist references by search criteria.
But if i using insertBefore, appendChild, etc... this function will remove the nodes from the elements.
Example i have a 4x4 table, and i want to return the first 2 rows:
var nl = document.createDocumentFragment();
el = document.querySelectorAll('tr');
for ( var a = 0; a < 2 && a < el.length; a++)
{
nl.appendChild(el[a]);
}
console.log(nl);
This nl returns the first 2 rows of the table, but it will removes from the document. Removed from the DOM and append to nl as child.
I want to retrieve only the node(s) reference like querySelectorAll as a list, not as documentFragment childNodes.
Any idea how to archieve this?

If you don't want to move things around in the DOM, don't use the methods that move things around!
var nl = new Array();
var el = document.querySelectorAll('tr');
for ( var a = 0; a < 2 && a < el.length; a++)
{
nl.push(el[a]);
}

Related

[variable].AddEventListener in Javascript?

I am very new to coding. Below is a piece of JS code i am struggling to understand:
var btnContainer = document.getElementbyId(“linkcontainer”);
var btns = btnContainer.getElementsbyClassName(“btn”);
for (var i = 0; i < btns.length; i++){
btns.addEventListener(“click”, function(){
var current = document.getElementsbyClassName(“active”);
current[0].className = current[0].className.replace(‘active’, “”);
this.className += ‘active’;
});}
What difference does the [i] make in
btns[i].AddEventListener??
What is it exactly and what if there was no “i” in between the brackets? Also current[0]. It’s probably a stupid question, but please help me understand.
First of all there are no stupid question but only stupid answers.
In your code you get a list of DOM elements stored in an array called 'btns', then you iterate it with a loop.
So btns[i] allow you to retrieves the elements at the i position (It's important to note that array start at 0 in Javascript).
Example:
var fruits = ['Apple', 'Banana'];
console.log(fruits[0])
console.log(fruits[1])
So if you don't use the [i] you will iterate on the array itself and not on the element stored in it.
As the name of the method getElementsByClassName suggests, this queries the DOM and returns an array like object that contain multiple elements with the class name that was specified.
btns - will be an array that contains one or more elements.
To access a specific element from the array, you access it using the index of the current iteration.
btns[1] - Gives you access to the 2nd element in the list.
addEventListener - is used to bind a event handler to a single element. You cannot directly use this on array of objects.
// query the DOM for element with id - linkcontainer
var btnContainer = document.getElementbyId(“linkcontainer”);
// query the DOM for elements with className - btn
// This can return multiple elements, so btns will be
// as array like object of elements
var btns = btnContainer.getElementsByClassName(“btn”);
// iterate over the array that was just queried for
for (var i = 0; i < btns.length; i++) {
// bind a click event for each element in the array
btns[i].addEventListener(“click”, function() {
// query the dom for elements with className - active
var current = document.getElementsByClassName(“active”);
// access the first element and replace the active class
current[0].className = current[0].className.replace(‘active’, “”);
// add the active class to the element that was clicked
this.className += ‘active’;
});
}
The way I see it you will have to remove the active class for all the elements instead of just the first entity. A slightly better way to improve this code would be is
var btnContainer = document.getElementbyId(“linkcontainer”);
var btns = btnContainer.getElementsByClassName(“btn”);
btns.forEach(function(btn) {
btn.addEventListener(“click”, function() {
// query the dom for elements with className - active
var current = document.getElementsByClassName(“active”);
current.forEach(function(elem) {
elem.classList.remove('active');
});
this.classList.add('active');
});
});
As the other posters have mentioned, your code var btns = btnContainer.getElementsbyClassName(“btn”); should return an array of DOM elements so in your for loop, btns[i] will retrieve the specific element at index i of btns as i goes from 0 to btns.length. Removing the i will retrieve the entire array on each iteration.
To your second question: current is exactly the same thing as btns, an array of DOM elements so current[0] will retrieve the first element in this array.

Get all the elements that start with a particular innerHTML using query selector?

I am currently having problem with selecting and matching the innerHTML using querySelectorAll.
Here is what i did:
document.querySelectorAll('*[class^="js-display-url"]').contains('product')
What the html is:
<span class="js-display-url">product/poss/newslanges</span>
But i want to match the class js-display-url starting with product but can't do that. please help.
With DOM selectors you cannot select elements based on the inner HTML, but you can loop through all the elements with that class and single out the ones that match your condition:
var allElements = document.querySelectorAll('*[class^="js-display-url"]');
var myElements = [];
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].innerHTML.startsWith('product')) {
myElements.push(allElements[i]);
}
}
There isn't a DOM selector which will filter based on text nodes, but you can filter using some array methods, since a NodeList is array-like.
In particular, Array.prototype.filter can get the elements that meet your criteria.
var filter = Array.prototype.filter;
var allElements = document.querySelectorAll('.js-display-url');
var productElements = filter.call(allElements, function(element) {
return element.innerText.startsWith('product');
});
console.log(productElements);
<span class="js-display-url">product/poss/newslanges</span>

Immediate nested DOM declaration in javascript

How can I get a nested DOM element in javascript instead of using jQuery?
Example:
$('#id') = document.getElementById('id');
I would like to convert this jQuery selector $('.nav > li') to javascript. How can I do that?
You have a really nice function called document.querySelectorAll() which can select elements with css queries.
document.querySelectorAll('.nav > li');
If you plan to use it more than once, you can also use a var so it'll feel like using jQuery
var _ = document.querySelectorAll.bind(document)
var menuItems = _('.nav > li');
Just to complement the answers suggesting querySelectorAll, here's how you would achieve that with old school DOM operations.
var selected = [];
// get all elements that have the class 'nav' (.nav)
var navs = document.getElementsByClassName('nav');
var i, j, children;
// iterate over each nav and get a list of their direct children (.nav >)
for(i = 0; i < navs.length; i++) {
children = navs[i].children;
// iterate over the children and select if the tag is li (.nav > li)
for(j = 0; j < children.length; j++) {
if(children[j].tagName === 'LI') {
selected.push(children[j]);
}
}
}
Also serves as a good example of why declarative programming is better suited to this kind of task.

I want to get only selected children array objected from jstree

Am using http://www.jstree.com
i used var nodes=$('#jstree').jstree("get_json"); this code and i got follow object as result
. I just want only get children as like this.
how to get that
You can use the get_json function, just pass in the optional ID (the node from which to begin):
var nodes=$('#jstree').jstree("get_json","NODE-ID-HERE").children;
Keep in mind this approach will give you the children of the children too, but you can simply ignore those. If that does now work for you - loop through the result and remove the children property.
var instance = $('#jstree').jstree(true),
children = instance.get_json("NODE-ID-HERE").children,
i, j;
for(i = 0, j = children.length; i < j; i++) {
delete children[i].children;
delete children[i].children_d;
}
// children is now an array of all the node's children, but without their children

Get all children of a node in javascript

I want to get all children of <p>.
HTML:
<p id="p">nodlist is an <i> ordered <b>collection of node</b> objects that are </i>children of the current element.<font color="blue"> If the element</font> has no children, then contains no node.</p>
JavaScript:
var childrens = [];
function getchilds(node){
if(node.nodeType == 1){
var childnodes = node.childNodes;
for(i=0; i<childnodes.length; i++){
var child = childnodes[i];
if(child.nodeType == 1)
getchilds(child);
}
}else
childrens.push(node);
}
var childnodes = document.getElementById('p').childNodes;
for(i=0; i<childnodes.length; i++){
getchilds(childnodes[i]);
}
but childrens[] is:
0 : nodlist is an
1 : ordered
2 : collection of node
3 : objects that are
4 : has no children, then contains no node.
children of the current element and If the element have missed, and when I add <a> element like link to p tag, the script gets stuck in an infinite loop.
Looks like you're using a global variable i for the loops which means you're going to miss elements when returning from an inner function call. Change it to
for(var i=0; i<childnodes.length; i++){
in both loops.

Categories