I want to access a span inside a div:
<div id="one">
<span>Hello</span>
</div>
<div id="oe">
<span>llo</span>
</div>
To access the span with Hello in CSS I would do this
#one>span{//CSS style}
What is the equivalent of this in javascript?
You can select this node with
document.querySelector('#one > span')
and if you have multiple nodes you can use querySelectorAll like this:
var nodes = document.querySelectorAll('#one > span');
for(var i = 0; i < nodes.length; i++) {
var node = nodes[i];
// do stuff with node here
}
One way is to use jQuery:
$('#one > span').get(); // as an array of elements
$('#one > span').get(0); // the first element (in your case, the 'Hello')
Related
So I have this HTML code and I need to select the elements by their name attribute. The problem is I have multiple elements with the same structure and I need to go throw them with a loop.
<div class="res">
<h4 name="title">title</h4>
<span name="span1"></span>
<span name="span2"></span>
<p name="p1"></p>
<p name="p2"></p>
</div>
I need to select each one of the elements inside the .res div element by their name(or if there's a better solution I'd like to you).
document.getElementsByName("res");
document.getElementsByName("title");
document.getElementsByName("span");
or you can loop through the elements if you don't want to hard-code the name.
You could use .querySelector() like :
document.querySelector('[name="xxxxxx"]');
If you want to loop through all the res containers you could use .querySelctorAll() like :
var containers = document.querySelectorAll('.res');
for( var i = 0; i < containers.length; i++) {
console.log( containers[i].querySelector('[name="title"]').textContent );
}
You can use the DOM Element.children attribute in pure javascript
var children = res.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
// Do stuff
}
You can use querySelectorAll and inside loop handle every element.
const elements = document.querySelectorAll(".res > *");
elements.forEach(element => {
console.log(element);
});
<div class="res">
<h4 name="title">title</h4>
<span name="span1"></span>
<span name="span2"></span>
<p name="p1"></p>
<p name="p2"></p>
</div>
I have an html document consists of a <div id = "main">. Inside this div may be several levels of nodes, without a precise structure because is the user who creates the document content.
I wanto use a JavaScript function that returns all nodes within div id = "main". Any tag is, taking into account that there may be different levels of children.
For now I have this function that returns all tags, even those outside to div id = "main":
function getNodes() {
var all = document.getElementsByTagName("*");
for (var elem = 0; elem < all.length; elem++) {
//do something..
}
}
As such this document:
<div id="main">
<h1>bla bla</h1>
<p>
<b>text text text </b> text text <i>text</i>.
<img src=".."></img>
</p>
<div>
<p></p>
<p></p>
</div>
<p>..</p>
</div>
The function getNodes would return an array of object nodes (I don't know how to represent it, so I list them):
[h1, p, b, i, img, div, p, p, p]
Thank you
Use document.querySelectorAll. It returns a NodeList, not an array, but you can loop over it in the same way:
function getNodes() {
var all = document.querySelectorAll("#main *");
for (var elem = 0; elem < all.length; elem++) {
//do something..
}
}
http://jsfiddle.net/suuja4L5/
Just get the parent element and then get the descendents just as you did:
var mainDiv = document.getElementById("main");
mainDiv.getElementsByTagName("*")
if you want all child of <div id="main">,then use the following :
var children = document.querySelector("#main").children;
I want to delete all elements that do not have the class 'stay'
For example:
<div class="stay">Stay</div>
<div class="stay">Stay</div>
<div class="go">Go</div>
<div class="element">Stay</div>
<div class="Sel">classy</div>
I would like some javascript that would delete the elements that do not have the class stay and Sel, without having to list the classes go and element
I have used:
var els = document.querySelectorAll('#parent :not(.stay)');
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i])
}
from the first answer, but am unsure of how to keep the class 'Sel'.
Also, I DO NOT want any Jquery.
When you are doing such an operation should need to target a particular parent element, else it could also remove elements like html/body etc.
So assuming you have a parent node, you can use querySelectorAll in conjunction with :not() selector
<div id="parent">
<div class="stay">Stay</div>
<div class="stay">Stay</div>
<div class="go">Go</div>
<div class="element">element</div>
</div>
then
var els = document.querySelectorAll('#parent :not(.stay)');
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i])
}
Demo: Fiddle
I have a div with span inside of it. Is there a way of counting how many elements in a div then give it out as a value. For Example there were 5 span in a div then it would count it and alert five. In Javascript please.
Thank you.
If you want the number of descendants, you can use
var element = document.getElementById("theElementId");
var numberOfChildren = element.getElementsByTagName('*').length
But if you want the number of immediate children, use
element.childElementCount
See browser support here: http://help.dottoro.com/ljsfamht.php
or
element.children.length
See browser support here: https://developer.mozilla.org/en-US/docs/DOM/Element.children#Browser_compatibility
You can use this function, it will avoid counting TextNodes.
You can choose to count the children of the children (i.e. recursive)
function getCount(parent, getChildrensChildren){
var relevantChildren = 0;
var children = parent.childNodes.length;
for(var i=0; i < children; i++){
if(parent.childNodes[i].nodeType != 3){
if(getChildrensChildren)
relevantChildren += getCount(parent.childNodes[i],true);
relevantChildren++;
}
}
return relevantChildren;
}
Usage:
var element = document.getElementById("someElement");
alert(getCount(element, false)); // Simply one level
alert(getCount(element, true)); // Get all child node count
Try it out here:
JS Fiddle
Without jQuery:
var element = document.getElementById("theElementId");
var numberOfChildren = element.children.length
With jQuery:
var $element = $(cssSelectocr);
var numberOfChildren = $element.children().length;
Both of this return only immediate children.
i might add just stupid and easy one answer
<div>this is div no. 1</div>
<div>this is div no. 2</div>
<div>this is div no. 3</div>
you can get how many divs in your doc with:
const divs = document.querySelectorAll('div');
console.log(divs.length) // 3
With jQuery; checks only for spans inside a div:
JSFiddle
$(function(){
var numberOfSpans = $('#myDiv').children('span').length;
alert(numberOfSpans);
})();
With jQuery you can do like this:
var count = $('div').children().length;
alert( count );
Here's a Fiddle: http://jsfiddle.net/dryYq/1/
To count all descendant elements including nested elements in plain javascript, there are several options:
The simplest is probably this:
var count = parentElement.getElementsByTagName("*").length;
If you wanted the freedom to add more logic around what you count, you can recurse through the local tree like this:
function countDescendantElements(parent) {
var node = parent.firstChild, cnt = 0;
while (node) {
if (node.nodeType === 1) {
cnt++;
cnt += countDescendantElements(node);
}
node = node.nextSibling;
}
return(cnt);
}
Working Demo: http://jsfiddle.net/jfriend00/kD73F/
If you just wanted to count direct children (not deeper levels) and only wanted to count element nodes (not text or comment nodes) and wanted wide browser support, you could do this:
function countChildElements(parent) {
var children = parent.childNodes, cnt = 0;
for (var i = 0, len = children.length; i < len; i++) {
if (children[i].nodeType === 1) {
++cnt;
}
}
return(cnt);
}
The easiest way is to select all the span inside the div which will return a nodelist with all the span inside of it...
Then you can alert the length like the example below.
alert(document.querySelectorAll("div span").length)
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
I have a block of code like this
<span class='Wrapper'>
<span class="title"></span>
<span class="body">
<ul class="items">
<li></li>
<li></li>
</ul>
<span>
</span>
Once I access the span wrapper element using document.getElementsByTagName('span');
how do I access the inner span elements with title class and the ul elements of the span element with class body.I need to do this using plain javascript
First get an array holding all the span elements:
var yourSpans = document.getElementsByTagName('span');
Then then loop over each element in the array checking if the element has the specific class:
for(var i in yourSpans){
if (yourSpans[i].className == "title" || yourSpans[i].className == "body") {
// your code here
}
}
var spans = document.getElementsByTagName('span');
would return an array of spans. You would access the spans using spans[0], spans[1], etc.
Adding to reagan's answer, you would then need to do something like
for( var i = 0, j= spans.length; i < j; i+=1 ) {
var classes = span[i].getAttribute("class");
if( classes ) {
if( classes.indexOf("your_class_name") != -1) {
//span[i] is one of thelements you need containing 'your_class_name'.
}
}
}
I would really recommend using jQuery, it would make your life a lot easier!
$('.title').dostuff...
But if you want a JS only solution, here you go...
function editClass(matchClass,content) {
var elems = document.getElementsByTagName('*'),i;
for (i in elems) {
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1) {
elems[i].innerHTML = content;
}
}
}
Here is a fiddle (Pure-JS, no jQuery) as an example.