Can you access the DOM children of an element using JS? - javascript

What I would like to do:
var myDIv = document.getElementById('myDivID');
myDIv.getImmediateChildren;

something like this:
var children = document.getElementById('myDivID').childNodes

Try Like this
var myDIv = document.getElementById('myDivID');
myDIv.Children;

To get all children, use :
myDiv.children
example here : https://jsfiddle.net/vgncd96t/
-
To get the first child, use :
myDiv.firstElementChild
example here : https://jsfiddle.net/vgncd96t/1/
-
To get the last child, use :
myDiv.lastElementChild
example here : https://jsfiddle.net/vgncd96t/2/

You can do something like:
var myDIv = document.getElementById('myDivID');
var children = myDiv.children;
That will get you all children of the element.
There are even more options, like if you want only the first child, you can do:
var firstChild = myDiv.firstElementChild;

document.getElementById("myDivID").children[0]
will give you the first immediate child element

Related

Get the tagName element inside class

I want to get the element of a inside class and change it.
My HTML is:
<div class="alignleft">
« Older Entries
</div>
I want to change Older Entries to Previous.
My JavaScript code is:
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
oldentries.ainside.innerHTML = "Previous";
but that gives me undefined.
Once you use Document.querySelector() to get the elements with class '.alignleft' you can also do oldentries.querySelector('a'); to get the 'a' element within oldentries and then change the element.innerHTML:
var oldentries = document.querySelector('.alignleft'),
ainside = oldentries.querySelector('a');
ainside.innerHTML = 'Previous';
<div class="alignleft">
« Older Entries
</div>
You need to update the textContent property of the <a> element.
Working Example:
var linkElement = document.querySelector('.alignleft a');
linkElement.textContent = 'Previous';
<div class="alignleft">
<a>Older Entries</a>
</div>
You can look for your element using a signle call to querySelector by using a more precise selector : Directly use .alignLeft a instead of doing it twice.
This code works :
var entries = document.querySelector('.alignLeft a');
entries.innerHTML = "Previous"
Your code would render out to something like
document.querySelector('.alignleft').document.getElementsByTagName('a').innerHTML = "Previous";
Also, getElementsByTagName('a') would render an Array not an object which you can apply .innerHTML to.
var ainside = document.querySelector('.alignlef a'); // Select first occurance of a inside the first occurance of .alignleft in the document
ainside.innerHTML = "Previous";
document.getElementsByTagName returns a HTML Collection. So you need to iterate over it (in your case it would be the first entry).
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
for(i=0;i<ainside.length;i++) {
ainside[i].innerHTML = "Previous";
}

Get first class of element

So let's I have a div with multiple classes like this:
<div class="s1 s"></div>
In the javascript I only want the first class, like
$(document.body).on('click','.s',function(){
var firstClass = //only get s1 from that one whole class.
});
How can I do this?
Try this:
$('.s').click(function()
{
var firstClass = $(this).attr('class').split(" ")[0];
});
Try This:
var firstClass = this.className.split(" ")[0];
No need to wrap it back into a jQuery element and incur the performance cost.

How to find an element in an array by attribute in jQuery

I need help finding an object in an array of jQuery selectors by attribute.
This is the code used for selection of the inputs elements in a table:
var tableInputs = $('#clienti-table input:not(#additionalAds)');
In variable tableInputs there are 13 input elements. I need to find each element by the id attribute.
Is there any way to do it?
Hope someone can help me.
Thanks in advance.
You can loop over the colleciton with .each():
tableInputs.each(function(){
var elem = this; //do something with this.
var id = elem.attr('id');
});
Or you can extract an element with a particular id, like this:
var $myElem = tableInputs.find('#myId');
... or by specifying the context in which to look for your element, like this:
var $myElem = $('#myId', tableElements);
You can use filter to get the element with a given id.
tableInputs.filter('#'+someid);// this gives you the element in the selection with id `someid`
You can use a for loop:
for (var i = 0; i < tableInputs.length; i++) {
console.log(tableInputs[i].id);
}
Try this... $('#clienti-table input:not([id='additionalAds']));
Please try using .find()
el = $('#clienti-table input:not(#additionalAds)').find('#id');
http://api.jquery.com/find/

Javascript Append Child AFTER Element

I would like to append an li element after another li inside a ul element using javascript, This is the code I have so far..
var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";
I am familiar with appendChild,
parentGuest.appendChild(childGuest);
However this appends the new element inside the other, and not after. How can I append the new element after the existing one? Thanks.
<ul>
<li id="one"><!-- where the new li is being put --></li>
<!-- where I want the new li -->
</ul>
You can use:
if (parentGuest.nextSibling) {
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
parentGuest.parentNode.appendChild(childGuest);
}
But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
You need to append the new element to existing element's parent before element's next sibling. Like:
var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
Or if you want just append it, then:
var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";
parentGuest.parentNode.appendChild(childGuest);
If you are looking for a plain JS solution, then you just use insertBefore() against nextSibling.
Something like:
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
Note that default value of nextSibling is null, so, you don't need to do anything special for that.
Update: You don't even need the if checking presence of parentGuest.nextSibling like the currently accepted answer does, because if there's no next sibling, it will return null, and passing null to the 2nd argument of insertBefore() means: append at the end.
Reference:
nextSibling
insertBefore
.
IF you are using jQuery (ignore otherwise, I have stated plain JS answer above), you can leverage the convenient after() method:
$("#one").after("<li id='two'>");
Reference:
jQuery after()
after is now a JavaScript method
MDN Documentation
Quoting MDN
The ChildNode.after() method inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes.
The browser support is Chrome(54+), Firefox(49+) and Opera(39+). It doesn't support IE and Edge.
Snippet
var elm=document.getElementById('div1');
var elm1 = document.createElement('p');
var elm2 = elm1.cloneNode();
elm.append(elm1,elm2);
//added 2 paragraphs
elm1.after("This is sample text");
//added a text content
elm1.after(document.createElement("span"));
//added an element
console.log(elm.innerHTML);
<div id="div1"></div>
In the snippet, I used another term append too
This suffices :
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);
since if the refnode (second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore
Actually I doubt that the || null is required, try it and see.
You could also do
function insertAfter(node1, node2) {
node1.outerHTML += node2.outerHTML;
}
or
function insertAfter2(node1, node2) {
var wrap = document.createElement("div");
wrap.appendChild(node2.cloneNode(true));
var node2Html = wrap.innerHTML;
node1.insertAdjacentHTML('afterend', node2Html);
}

How to get all element parents using jquery?

How to get all element parents using jquery? i want to save these parents in a variable so i can use later as a selector.
such as <div><a><img id="myImg"/></a></div>
GetParents('myImg'); will return "div a" something like that
/// Get an array of all the elements parents:
allParents = $("#myElement").parents("*")
/// Get the nested selector through an element's parents:
function GetParents(id) {
var parents = $("#" + id).parents("*");
var selector = "";
for (var i = parents.length-1; i >= 0; i--) {
selector += parents[i].tagName + " ";
}
selector += "#" + id;
return selector;
}
GetParents('myImage') will return your nested selector: HTML BODY DIV A #myImage
Note sure why you'd want this but its reuseable as a selector.
You don't need to grab their selectors, as you can use them directly with jQuery afterwards.
If you want to use all parents later, you can do something like:
var parents = $("#element").parents();
for(var i = 0; i < parents.length; i++){
$(parents[i]).dosomething();
}
Every element has only one real parent. To access and save it, write the following:
myParent = $("#myElement").parent();
If you need the parents parents too, use .parents()
See documentation for further information:
http://docs.jquery.com/Traversing/parent#expr
http://docs.jquery.com/Traversing/parents#expr
You can use parents() to get your immediate parent, and their parents on up the tree. you can also pass a selector as an arg to only get parents that match a certain criteria. For instance:
$('#myelement').parents('[id$=container]')
to get all parents who have an id attribute whose value ends with the text "container"
You can get all the tags of an element's parents like this:
var sParents = $('#myImg').parents('*').map(function() {
return this.tagName;
}).get().join(' ');
you can also replace this.tagName with this.id for example or other attributes

Categories

Resources