I have 2 divs by class name tag which contain p,span tags . So when I trigger an onclick event on a div they should log or show the content of p, span tags.
But when I am doing that it gives all the content of say 2 divs that I have in my markup.
How do I go by that when I click on that particular div the content of p, span tags of that clicked div should be displayed and not of all the p, span tags.
var tag = document.getElementsByClassName("tag");
var pTag = document.querySelectorAll("P");
var sTag = document.querySelectorAll("SPAN");
for (var i = 0; i < tag.length; i++) {
tag[i].onclick = function() {
for (var j = 0; j < pTag.length; j++) {
console.log(pTag[j].innerHTML);
}
}
}
<div class="tag">
<p>Head Text-1</p>
<span>10</span>
</div>
<div class="tag">
<p>Head Text-2</p>
<span>20</span>
</div>
onclick should be inside for loop. Also to get the text you should use textContent instead of innerHTML:
var tag = document.getElementsByClassName("tag");
var pTag = document.querySelectorAll("P");
var sTag = document.querySelectorAll("SPAN");
for (var i = 0; i < tag.length; i++) {
for (var j = 0; j < pTag.length; j++) {
tag[i].onclick = function() {
console.log(this.textContent);
}
}
}
<div class="tag">
<p>Head Text-1</p>
<span>10</span>
</div>
<div class="tag">
<p>Head Text-2</p>
<span>20</span>
</div>
this will solve your issue
var tag = document.getElementsByClassName("tag");
var pTag = document.querySelectorAll("P");
var sTag = document.querySelectorAll("SPAN");
function showContent(event){
console.log(event.lastElementChild.innerText);
}
<div class="tag" onclick="showContent(this)">
<p>Head Text-1</p>
<span>10</span>
</div>
<div class="tag" onclick="showContent(this)">
<p>Head Text-2</p>
<span>20</span>
</div>
What you want is to get your tag's textContent, But instead, your tag.onclick show the entire document's p elements (which is your pTag in your question).
Following is a sample how you can select the children element's p and span of the clicked .tag
var tags = document.getElementsByClassName("tag");
for (var i = 0; i < tags.length; i++) {
tags[i].onclick = function () {
var self = this,
childParagraphs = [].filter.call(document.querySelectorAll("p"), function(elem) {
return elem.parentNode === self;
}),
childSpans = [].filter.call(document.querySelectorAll("span"), function(elem) {
return elem.parentNode === self;
});
for (var j = 0; j < childParagraphs.length; j++) {
console.log('childParagraph: ', childParagraphs[j].innerHTML);
}
for (var j = 0; j < childSpans.length; j++) {
console.log('childSpan: ', childSpans[j].innerHTML);
}
}
}
<div class="tag">
<p>Head Text-1</p>
<span>10</span>
</div>
<div class="tag">
<p>Head Text-2</p>
<span>20</span>
</div>
Or, if you really just need the whole text of the entire .tag, you can use #Mamun answer by using textContent.
Related
<div id="random numbers">
<div class="column-1"></div>
<div class="column-1">this value I want to change</div>
<div class="column-1"></div>
</div>
from earlier advice, I have this code:
var elements = document.querySelectorAll('.column-1 a');
for (var i = 0; i < elements.length; i++) {
elements[i].outerHTML = "OVERRIDDEN";
}
the issue I'm having is that this replaces each <a inside each div <div id="random numbers">), while I would like it only to replace the second column-1 inside each random numbers div.
thank you in advance!
document.querySelectorAll('.column-1 a')[1].outerHTML = "OVERRIDDEN";
Just work with i
var elements = document.querySelectorAll('.column-1');
for (var i = 0; i < elements.length; i++) {
if(i%2) { // override 2nd, 4th, etc.
elements[i].outerHTML = "OVERRIDDEN";
}
}
https://jsfiddle.net/ishukshin/av6t6kxz/
I am trying to append new div elements to existing divs by using document.getElementsByTagName("div"), converting it to an array, then using appendChild on it. However, when I inspect the frame source of this jsfiddle, it doesn't seem to append it to the divs. It is just:
<body>
<div id="1">
<div id="2">
test
</div>
</div>
Instead of the expected result:
<body>
<div id="1">
<div id="2">
test
</div><div></div>
</div><div></div>
https://jsfiddle.net/ng58e87w/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
I can't comment, but I believe you are just creating empty divs and adding nothing to them. They show up created when you inspect element in the jsfiddle. I also set their text to something and it seemed to work.
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "Hidden Div?";
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
Use .after() instead of .appendChild().
var words = ['apple','banana','cake'];
console.log(words[0]);
object1 = {
name:'frank',
greet:function(){
alert('hello '+this.name)
}
};
object2 = {
name:'andy'
};
// Note that object2 has no greet method.
// But we may "borrow" from object1:
object1.greet.call(object2);
/*
var divs = [];
var arr = Array.prototype.slice.call( document.getElementsByTagName("div") );
for(var i = 0; i < arr.length; i++) {
//do something to each div like
var div = document.createElement("div");
arr[i].appendChild(div);
}
*/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].after(newDiv);
console.log(allDivs[i]);
}
<div id="1">
<div id="2">
test
</div>
</div>
I'm trying to build a script that detects the particular <span> the user clicks on and outputs the value of the contents of that clicked span.
My HTML looks like this:
<div id="span-container">
<span>Lorem</span>
<span>Ipsum</span>
<span>Something...</span>
<span>Something...</span>
<span>Amet</span>
</div>
And my Javascript looks like this:
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].onclick = function() {
alert(spans[i].innerHTML);
}
}
Attempting to run this code results in a Cannot read property 'innerHTML' of undefined error.
I'm sure giving each span an ID that correlates to its contents like <span id="lorem">Lorem</span> would work, but I'm optimistic that a more elegant solution exists.
I'd also like to avoid using jQuery if possible.
Thanks!
Use event delegation:
var div = document.getElementById('span-container');
div.addEventListener('click', function(e) {
var target = e.target;
if(target.nodeName == 'SPAN') {
alert(target.innerHTML);
}
});
Wrapping it
The problem is, i has changed by the time the user click on it. Use a self-executing function or eventListener
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
(function (j) {
spans[j].onclick = function() {
alert(spans[j].innerHTML);
}
}(i));
}
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
(function (j) { // Receives as j
spans[j].onclick = function() {
alert(spans[j].innerHTML);
}
}(i)); // Passes in i
}
<div id="span-container">
<span>Lorem</span>
<span>Ipsum</span>
<span>Something...</span>
<span>Something...</span>
<span>Amet</span>
</div>
Using this
this will refer to the element clicked and is probably the best way to do this:
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].onclick = function() {
alert(this.innerHTML);
}
}
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].onclick = function() {
alert(this.innerHTML);
}
}
<div id="span-container">
<span>Lorem</span>
<span>Ipsum</span>
<span>Something...</span>
<span>Something...</span>
<span>Amet</span>
</div>
The problem here is the wrong use of a closure variable in a loop
But I think in this case you can use addEventListener
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
function spanClickHandler() {
alert(this.innerHTML);
}
for (var i = 0; i < spans.length; i++) {
spans[i].addEventListener('click', spanClickHandler, false);
}
<div id="span-container"> <span>Lorem</span>
<span>Ipsum</span>
<span>Something...</span>
<span>Something...</span>
<span>Amet</span>
</div>
or just use this.innerHTML as this inside the event handler refers to the span element
spans[i].onclick = function () {
alert(this.innerHTML);
}
JavaScript closure inside loops – simple practical example
You can use this for the current element.
Try this code:
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].onclick = function() {
alert(this.innerHTML);
}
}
I have got a task to set the menu as selected. For that I use dynamic id.
So I want to increment it with respect to the selection
My code is
<div class="menuHeader ui-corner-top" id="menu"+ i>
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top" id="menu"+ i>
<span>New Transaction</span>
</div>
<div class="menuHeader ui-corner-top" id="menu"+ i>
<span>Portfolio</span>
</div>
javascript is
$(document).ready(function () {
alert(document.URL);
var list = $("#menu");
for (var i = 1; i <= list.length; i++) {
list[i].innerHTML = i;
}
var str = document.URL.toLowerCase().indexOf("portfolio/index");
alert(str);
if (str >= 0) {
$('#menu').addClass("menuHeaderActive");
}
});
How can I do this?
var i=0;
$('.menuHeader').each(function(){
i++;
var newID='menu'+i;
$(this).attr('id',newID);
$(this).val(i);
});
This is the way to do it with Jquery
val elementList = $(".menu");
for (var i = 1; i <= list.length; i++) {
elementList[i].attr("id", "menu" + i);
}
Just use a class name instead of an id, you will be able to reuse the code you have just added but in this way.
var list = $(".menu");
One advice, don't do the highlighting of the item menu with javascript, do it server-side, and you can add the "activating" class directly in the HTML of the LI.
How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}