Why this code is not working ?
I think i am doing some silly mistake here.
document.addEventListener("DOMContentLoaded", function() {
var text = "Planing";
document.getElementsByTagName("div").innerHTML = text;
});
<div id="demo" class="eg"></div>
getElementsByTagName returns a collection of all the matching elements(<div>s in this case) on the page/DOM, to select first element use array notation with zero index.
document.addEventListener("DOMContentLoaded", function() {
var text = "Planing";
document.getElementsByTagName("div")[0].innerHTML = text;
});
<div id="demo" class="eg"></div>
If you want to select first element, you can use document.querySelector('div');
If you want to perform some operation on all the selected elements, you need to iterate over them.
var allDivs = document.getElementsByTagName("div");
for (var i = 0; i < allDivs.length; i++) {
allDivs[i].innerHTML = 'Div ' + i;
}
getElementsByTagName, as the name suggests returns an array of elements (even if there is just one). You need to access the first one before applying the text.
document.addEventListener("DOMContentLoaded", function() {
var text = "Planing";
document.getElementsByTagName("div")[0].innerHTML = text;
});
<div id="demo" class="eg"></div>
Related
I'm fairly new to JS and I can do DOM manipulation and if/else statements by hand. Now I'm trying for something out of my league, combining iteration with arrays, and I have a bit of a hard time understanding both of them.
With this in mind: Considering this div: <div id="firstAnchor"> would act as an anchor to this link:
I want to store the ID of these div's (id's should be able to be anything):
<div id="firstAnchor" style="display: inline-block;">First title</div>
<div id="secondAnchor" style="display: inline-block;">Second title</div>
<div id="thirdAnchor" style="display: inline-block;">Third title</div>
into an array, and then create these three links automatically* placed in a div called "anchorLinks":
Link to first title
Link to second title
Link to third title
How would I go about this?
*
for example within this function:
(function create_anchor_link_list() {
//placed here
})();
Edit:
Here is what I have tried to begin with. I first had data-anchor="firstAnchor" etc. on my div elements until I realized I couldn't link to div elements based on data- attributes values. So with the data- attributes I tried:
(function anchorsInPage2(attrib) {
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log("=#=#=#=#=# anchorsInPage2 function #=#=#=#=#");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log(" ");
var elements = document.getElementsByTagName("*");
var foundelements = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].attributes.length > 0) {
for (var x = 0; x < elements[i].attributes.length; x++) {
if (elements[i].attributes[x].name === attrib) {
foundelements.push(elements[i]);
}
}
}
}
return foundelements;
console.log(" ");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log("=#=#=#=#=# / anchorsInPage2 function #=#=#=#=#");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
})();
function anchorsInPage3() {
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log("=#=#=#=#=# anchorsInPage3 function #=#=#=#=#");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log(" ");
var elements = document.getElementsByTagName("*");
var foundelements = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].attributes.length > 0) {
for (var x = 0; x < elements[i].attributes.length; x++) {
if (elements[i].attributes[x].name === "anchor") {
foundelements.push(elements[i]);
}
}
}
}
return foundelements;
console.log(" ");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log("=#=#=#=#=# / anchorsInPage3 function #=#=#=#=#");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
}
(function anchorsInPage1() {
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log("=#=#=#=#=# anchorsInPage1 function #=#=#=#=#");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log(" ");
var anchors = document.querySelectorAll('[anchor]');
for(var i in anchors){
console.log(i);
}
console.log(" ");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
console.log("=#=#=#=#=# / anchorsInPage1 function #=#=#=#=#");
console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
})();
First update after further testing:
Barmar's example was used. The text below is a direct answer to Barmar (too long for the other comment field)
Test: http://jsfiddle.net/e5u03g4p/5/
My reply:
With the first variable you found all element with the attribute data-anchor, so I guess the brackets in querySelectorAll tells it which specific attribute we mean instead of what elements ID's we want, which is the "standard" writing document.querySelectorAll("tagName") instead of document.querySelectorAll("[attributeName]").
With the second variable you found the first element with the ID of anchorLinks. The hashtag is needed to specify ID as querySelector represents div so the result is div#anchorLinks(?).
You then take the variable anchors (which results in an array of the data-anchor value of the div's with the data-anchor attribute) and for each of them, a function triggers where the d argument of the function equals the element ID of the elements with the data-anchor attribute. Everything within this function repeats for each of the elements with data-anchor attribute (ie. the variable anchors).
What's happening within the function is:
-You create a variable (a) which contains the element creation of an <a> element
-You then set the href attribute of the newly created <a> element to the ID
of the data-anchor elements.
-I then assign the attribute title of the <a> elements to the content of the data-anchor elements (instead of the original thought where it was textContent that was set to the <a> elements`as I want the links to be images instead of text)
-I then also added a new class attribute to the <a> elements in order to style them
If you used data-anchor="something" in your DIVs, then you should use
var anchors = document.querySelectorAll('[data-anchor]');
not [anchor].
You can then loop over them with forEach()
var anchorLinks = document.querySelector("#anchorLinks");
anchors.forEach(function(d) {
var a = document.createElement('a');
a.href = '#' + d.id;
a.textContent = 'Link to ' + d.textContent.toLowerCase();
anchorLinks.appendChild(a);
});
If you craft the query selector correctly you can get all of the "anchor" elements at once, then iterate over them to add the relevant links.
var links = document.getElementById('anchorLinks');
document.querySelectorAll('#anchors div[id]').forEach(function(anchor) {
var link = document.createElement('a');
link.href = '#' + anchor.id;
link.textContent = 'Link for ' + anchor.textContent;
links.appendChild(link);
});
<div id="anchors">
<div id="firstAnchor" style="display: inline-block;">First title</div>
<div id="secondAnchor" style="display: inline-block;">Second title</div>
<div id="thirdAnchor" style="display: inline-block;">Third title</div>
</div>
<div id="anchorLinks">
</div>
How about this:
document.getElementsByTagName('div').forEach(function(d) {
var a = document.createElement('a');
a.setAttribute('href', '#' + d.id);
a.innerHTML = 'Link to ' + d.textContent.toLowerCase();
document.getElementById('anchorLinks').appendChild(a);
});
Or if you have more divs (of course) and they have a specific class, you can do:
document.getElementsByClassName('your-class-name').forEach(function(d) {
var a = document.createElement('a');
a.setAttribute('href', '#' + d.id);
a.innerHTML = 'Link to ' + d.textContent.toLowerCase();
document.getElementById('anchorLinks').appendChild(a);
});
It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculation.
The question how to get values so when I click on spans it will show it in the second field
Here is the code.
http://jsfiddle.net/ovesyan19/vb394983/2/
<span>(</span>
<span>)</span>
<span class="delete">←</span>
<span class="clear">C</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">÷</span>
....
JS:
var keys = document.querySelectorAll(".keys span");
keys.onclick = function(){
for (var i = 0; i < keys.length; i++) {
alert(keys[i].innerHTML);
};
}
var keys = document.querySelectorAll(".keys span");
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function(){
alert(this.innerHTML);
}
}
keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.
Fiddle
This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.
Fiddle Update: http://jsfiddle.net/vb394983/3/
JavaScript (jQuery):
$(".keys").on("click","span",function(){
var clickedVal = $(this).text();
$(".display.result").append(clickedVal);
});
You can set a click event on the span elements if you use JQuery.
Eg:
$("span").click(
function(){
$("#calc").val($("#calc").val() + $(this).text());
});
See:
http://jsfiddle.net/vb394983/6/
That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.
http://jsfiddle.net/vb394983/7/
var v="",
max_length=8,
register=document.getElementById("register");
// attach key events for numbers
var keys = document.querySelectorAll(".keys span");
for (var i = 0; l = keys.length, i < l; i++) {
keys[i].onclick = function(){
cal(this);
}
};
// magic display number and decimal, this formats like a cash register, modify for your own needs.
cal = function(e){
if (v.length === self.max_length) return;
v += e.innerHTML;
register.innerHTML = (parseInt(v) / 100).toFixed(2);
}
Using JQuery will make your life much easier:
$('.keys span').click(function() {
alert(this.innerHTML);
});
I want to use pure JavaScript to hide all content inside brackets in a document. For example, this:
Sometext [info]
would be replaced with this:
Sometext
With jQuery I can do this with:
<script type="text/javascript">
jQuery(document).ready(function(){
var replaced = jQuery("body").html().replace(/\[.*\]/g,'');
jQuery("body").html(replaced);
});
</script>
The document's DOMContentLoaded event will fire at the same time as the callback you pass to jQuery(document).ready(...).
You can access the body of the page through document.body instead of jQuery("body"), and modify the HTML using the .innerHTML property instead of jQuery's .html() method.
document.addEventListener("DOMContentLoaded", function(event) {
var replaced = document.body.innerHTML.replace(/\[.*\]/g,'');
document.body.innerHTML = replaced;
});
If you use, document.body.innerHTML to replace, it is going to replace everything between [], even valid ones like input names. So I think what you need is to grab all of the textnodes and then run the regex on them. This question looks like it will do the trick.
function recurse(element)
{
if (element.childNodes.length > 0)
for (var i = 0; i < element.childNodes.length; i++)
recurse(element.childNodes[i]);
if (element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue)){
element.nodeValue = element.nodeValue.replace(/\[.*\]/g,'');
}
}
document.addEventListener('DOMContentLoaded', function() {
// This hits the entire document.
// var html = document.getElementsByTagName('html')[0];
// recurse(html);
// This touches only the elements with a class of 'scanME'
var nodes = document.getElementsByClassName('scanME');
for( var i = 0; i < nodes.length; i++) {
recurse(nodes[i]);
}
});
You already have the solution, try "Sometext [info]".replace(/\[.*\]/g,'');
Basically what your doing is this
document.addEventListener('DOMContentLoaded', function() {
var replaced = document.body.innerHTML.replace(/\[.*\]/g,'');
document.body.innerHTML = replaced
});
That would be a silly idea though (speaking for myself)
Make your life easier & your site better by doing something like this
<p> Sometext <span class="tag-variable"> [info] </span> </p>
document.addEventListener('DOMContentLoaded', function(){
var tags = document.getElementsByClassName('tag-variable');
for( var i = 0; i < tags.length; i++) {
var current = tags[i]; // Work with tag here or something
current.parentNode.removeChild( current );
}
});
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 an html code like this
<div>
<p> blah blah </p>
<div class = foo>
//some code
</div>
//some text
</div>
What i want to do by javascript is to add a wrapper div to the inner div with class foo. So that the code becomes something like
<div>
<p> blah blah </p>
<div id = temp>
<div class = foo>
//some code
</div>
</div>
//some text
</div>
Please tell me how to do something like this. Non jquery solutions would be more helpful.. :)
Using POJS is pretty simple:
function divWrapper(el, id) {
var d = document.createElement('div');
d.id = id;
d.appendChild(el);
return d;
}
Make sure you pass it something that can be wrapped in a div (e.g. don't give it a TR or TD or such).
You'll need some helper functions, I'm not going to post a getElementsByClassName function here, there are plenty on the web to choose from, a good one should first try qSA, then DOM method, then custom function.
Assuming you have one, consider something like:
function wrappByClass(className) {
var el, elements = getElementsByClassName(className);
for (var i = elements.length; i--;) {
el = elements[i];
el.parentNode.replaceChild(divWrapper(el, 'foo' + i), el);
}
}
Edit
On reflection, I prefer the following method. It inserts the wrapper div into the DOM first, then moves the element to be wrapped into it. The above seems to move the element out of the DOM, then wants to use its position in the DOM to insert the new node. It might work, but seems prone to error to me. So here's a better solution, tested in Safari:
// Quick implementation of getElementsByClassName, just for prototypeing
function getByClassName(className, root) {
var root = root || document;
var elements = root.getElementsByTagName('*');
var result = [];
var classRe = new RegExp('(^|\\s)' + className + '(\\s|$)');
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (classRe.test(elements[i].className)) {
result.push(elements[i]);
}
}
return result;
}
var divWrapper = (function() {
var div = document.createElement('div');
return function(el, id) {
var oDiv = div.cloneNode(false);
oDiv.id = id;
el.parentNode.insertBefore(oDiv, el);
oDiv.appendChild(el);
}
}());
function wrapByClassName(className) {
var els = getByClassName(className);
var i = els.length;
while (i--) {
divWrapper(els[i], 'foo' + i)
}
}
var wrapper = document.createelement('div');
var myDiv = document.getelementById('myDiv');
wrapper.appendChild(myDiv.cloneNode(true));
myDiv.parentNode.replaceChild(wrapper, myDiv);
$('.foo').wrap('<div id="temp"/>');
See $.wrap()
Note that if there are more elements than 1 wrapped, you got more elements with the ID "temp"