I need to add an EventListener function on every div with a certain class, I tried this:
var a = document.getElementsByClassName('linkto');
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
console.log(a);
}); }
But that gives me all the divs. My divs are generated in a foreach loop:
#foreach($faqs['My_Stay'] as $faqheading)
<div class="row lowboarder linkcolor-darkblue linkto">
{{ link_to('#div'.$faqheading->id,$faqheading->heading) }}
</div>
#endforeach
Is there a good way to determine which div was clicked on?
try like below, "this" inside your click function refer to the clicked div
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
console.log(this.innerText);
}); }
Related
I'm trying to apply the onclick event with JavaScript to the following elements:
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
If I click on the first element (with index [0]) then this works, but I
need this event applicable for all classes:
document.getElementsByClassName('abc')[0].onclick="function(){fun1();}";
function fun1(){
document.getElementsByClassName('abc').style.color="red";
}
.onclick does not expect to receive a string, and in fact you don't need an extra function at all.
However, to assign it to each element, use a loop, like I'm sure you must have learned about in a beginner tutorial.
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
this.style.color = "red";
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
To expand on the solution provided by #rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.
Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
var oldLink = document.getElementsByClassName('red')[0];
if(oldLink) {oldLink.classList.remove('red')};
this.classList.add('red');
}
.red {
color:red;
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
This works:
<body>
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
<script>
var elements = document.getElementsByClassName('abc');
for(var i = 0, max = elements.length; i < max; i += 1) {
var clickedElement = elements[i];
clickedElement.onclick=function (){
fun1(this);
};
}
function fun1(element){
element.style.color="red";
}
</script>
</body>
I have a huge problem here.
I can't get my onclick to work as I want .. So I hope someone here can help me.
#NiceToKnow
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="video"></div>
I want it to display: none; every of my class="nice", so you only can see class="video", but nothing happens at all.
You are selecting the elements of the class not the class itself. So you will have to loop through the elements as javascript can only edit what is in the DOM not the CSS classes that effect your elements. So getElementsByClassName returns an array of nodes in which we must loop through and hide each one. Click runsnippet below to see this work
function changeNice(){
//ASSIGN ELEMENTS TO ARRAY
elementsofClass=document.getElementsByClassName('nice');
for(i=0; i<elementsofClass.length; i++){
//HIDE SELECTED ELEMENT
elementsofClass[i].style.display='none';
}}
#NiceToKnow
<div id="cards1" class="nice">TEST 1</div>
<div id="cards2" class="nice">TEST 2</div>
<div id="cards3" class="nice">TEST 3</div>
<div id="cards4" class="video">I don't HIDE</div>
Also don't use duplicate ID. This will cause errors later when trying to select your elements.
The getElementsByClassName will return an array, so we need to iterate through the array and hide one by one.
So it is better to declare a function and define the logic inside that. Please see the example below.
window.hideAllniceClass = function () {
var elems = document.getElementsByClassName('nice');
for (var i = 0; i != elems.length; ++i) {
elems[i].style.display = "none"; // hidden has to be a string
}
}
#NiceToKnow
<div id="cards1" class="nice">Test Content</div>
<div id="cards2" class="nice">Test Content</div>
<div id="cards3" class="nice">Test Content</div>
<div id="cards4" class="video">Test Video Content</div>
DEMO
Change your code to something like that:
var elems = document.getElementsByClassName('nice');
for(var i = 0; i < elems.length; i++) {
elems[i].style.display = 'none'
}
You have to iterate on the results returned by getElementsByClassName.
jsfiddle
You can create a loop that will loop through all the nice elements and then display none like this: https://jsfiddle.net/7vf9pz8u/
<script>
function hide(){
for(ct=0; ct < 3; ct++){
document.getElementsByClassName('nice')[ct].style.display='none'
}
}
</script>
getElementsByClassName returns array of all the match elements so you will have to provide index or loop through all of them to change their property.
Change your code to this
document.getElementsByClassName('nice')[0].style.display='none'
//For every element
var e = document.getElementsByClassName('nice');
for (i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
As your divs do not have unique names they are in an array cards[].
So to access a particular div you need to reference the the array to that particular div. The quoted solution should work.
I need to access span inside div by using document.getElementsByClassName().
I have-
<div class="PERSON">
<span class="name">Person_name</span>
<span class="title">Person_title</span>
<span class="team">Person_team</span>
</div>
I need to access all spans with class team within all divs with class PERSON. How do I do it?
I have the following code -
function dispTeam(tname)
{
alert(tname);
var e=document.getElementsByClassName("PERSON");
for(var m=0;m<e.length;m++)
{
if(e[m].document.getElementsByClassName("team").innerHTML.indexOf(tname)==-1)
{
e[m].style.display="none";
}
else
{
e[m].style.display="block";
}
}
}
The alert is getting triggered but the elements are not getting displayed.
NOTE: There are divs with class PERSON which do NOT have span with class team. I need to include those divs in this condition too.
If they don't have span class team, those divs must not be displayed.
Use this code instead:
dispTeam=function(tname)
{
var divs=document.getElementsByTagName("div");
for(var i=0; i<divs.length; i++)
divs[i].style.display='none';
var span=document.querySelectorAll(".PERSON>.team");
for(var i=0; i<span.length; i++)
{
if(span[i].innerHTML.indexOf(tname)!=-1)
span[i].parentNode.style.display='block';
}
}
DEMO
Read More: querySelector() and querySelectorAll()
HTML:
<div class="page">111111</div>
<div class="page">222222</div>
<div class="page">333333</div>
<div class="page">444444</div>
<div class="page">555555</div>
JavaScript:
var div = document.getElementsByClassName("page");
for (i = 0; i < div.length; i++) {
bt = document.createElement("button");
bt.innerHTML = "kill my followings";
div[i].appendChild(bt);
bt.onclick = function (i) {
return function () {
kill(div[i]);
}
}(i);
}
function kill(obj) {
// ...
}
See FIDDLE here.
I constructed some divs which class="page". I used JavaScript to add buttons to each div, and add onClick event to each of them.
I need to remove the divs after my current operating div. e.g, If user click button in No.3 div, No.4 and 5 should be removed.
How to realized it?
(if not necessary, the structure of original html is not allowed to change)
Thanks a lot!
This should be the simplest way to go:
function kill(obj) {
while (obj.nextSibling) {
obj.parentNode.removeChild(obj.nextSibling);
}
}
DEMO: http://jsfiddle.net/BtSKJ/3/
I have a series of divs of the same class; some with title attributes set - some without:
<div class="component_wrapper cw1" title="thisTitle1">... </div>
<div class="component_wrapper cw2" title="thisTitle2">... </div>
<div class="component_wrapper cw3" title="thisTitle3">... </div>
<div class="component_wrapper cw4" title="">... </div>
<div class="component_wrapper cw5" title="">... </div>
I've constructed a javascript function that loops through these divs and displays the ones with the title attribute set by setting their css display attribute to "inline":
function checkComponent(e){
var hdrSet = document.getElementsByClassName("component_wrapper");
var titles = {};
for (var i=0; i<hdrSet.length; i++){
if ( !titles[ hdrSet[i].title ] ) {
titles[ hdrSet[i].title ] = true;
hdrSet[i].style.display = "inline";
}
}
}
checkComponent();
the problem is, when I load the page the divs that I'm trying to target display (good), but also 1 of the divs not targeted displays. In the example above, the first four divs display, when all I want is the first three. What's wrong with my code... and is there an better way to construct the function?
Your code checks for duplicate titles, not missing ones. Here's how you could fix that:
function checkComponent(){
var hdrSet = document.getElementsByClassName("component_wrapper");
for (var i = 0; i < hdrSet.length; i++){
if(hdrSet[i].title) {
hdrSet[i].style.display = "inline";
}
}
}
checkComponent();
Also, if you're open to using jQuery, it's much neater and more compatible:
function checkComponent() {
$('.component_wrapper[title]:not([title=""])').css('display', 'inline');
}
checkComponent();