getElementsByTagName in JavaScript [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I'm new to the syntax of pure JavaScript; Do you know why "getElementsByTagName" is not working in my simple test:
var btn = document.getElementsByTagName('button');
console.log(btn);
btn.onclick=function(){
alert('entered');
document.getElementById("demo").innerHTML="test";
}
Fiddle

getElementsByTagName returns an array, not a single element. You need to loop through your results and attach a function to each one individually, something like this:
var buttons = document.getElementsByTagName('button');
for( var x=0; x < buttons.length; x++ ) {
buttons[x].onclick = function(){
alert('entered');
document.getElementById("demo").innerHTML="test";
};
}

Should be
var btn = document.getElementsByTagName('button')[0];
instead of
var btn = document.getElementsByTagName('button');
getElementsByTagName returns array of matched elements. So use 0 index to access the button.
More about getElementsByTagName()
OR
You can provide the specific id on button and can use getElementById()
JS
var btn = document.getElementById('myButton');
HTML
<button id="myButton">....</button>

getElementsByTagName()
returns an array, which you have to access by their index.
For selecting a single element, use getElementById('id here');
The method itself says get Elements.

Just replace btn by btn[0] like this-
btn[0].onclick=function(){
alert('entered');
document.getElementById("demo").innerHTML="test";
}

Related

Fade In random quote's from array [duplicate]

This question already has answers here:
CSS transition fade in
(4 answers)
Closed 3 years ago.
I need to get quotes to Fade In when clicking on the Get Quotes button. I am very new to JS and CSS and feel relatively lost. I also want to do this not using Jquery.
var quoteText = document.querySelector("h2");
var authorText = document.querySelector("h3")
var button = document.querySelector("button");
var body = document.querySelector("body");
button.addEventListener("click", function(){
var colorRandom = Math.floor(Math.random()*255)
var random = Math.floor(Math.random()*quotes.length)
quoteText.textContent = quotes[random];
authorText.textContent = "- " + authors[random];
})
First, if you want to get all (more than one) quotes you have to use querySelectorAll(), because they querySelector() method returns the first element. When you get all elements you can return random index in range of nodeList.length.
This is very simple example in https://codepen.io/iganchev87/pen/vqxjNm . If you want you can add in function with event listener and so on.
I hope it will help you.
var allQuotes = document.querySelectorAll("h2");
var randomIndex = Math.floor(Math.random()*(allQuotes.length));
console.log(allQuotes[randomIndex].textContent);

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";
}

How can I find an element by onclick attribute value?

I am wondering if it is possible to find an element by the onclick function?
For example:
<a class = "calculator" onclick = add(number1,number2);
<a class = "calculator" onclick = add(number2, number3);
And I want to get the first one and the only difference is the onclick function so I thought thats the way I could differ them. Looks so far like this:
var elements = document.getElementsByClassName("calculator");
console.log(elements);
for (var i = 0; i < elements .length; ++i) {
elementsSpecific = elements[i]. //The missing part
console.log(delementsSpecific);
}
You can, though I wouldn't recommend it. It's faster to use different ids. However, if you really want to do it this way...
var link = document.querySelector('a[onclick="add(number1,number2)"]');
If you don't understand it, read about querySelector
You can get the onclick function by using
elements[i].getAttribute('onclick');
This is a pretty poor way of targeting elements (what if the onclick value changes?) but if it's all you've got then you can use an attribute selector and querySelector:
var el = document.querySelector('a[onclick="add(number1,number2);"]');
I would definitely exhaust other avenues of selection before resorting to this, however.
Without using js frameworks and making it for crossbrowser you can do this.
var as = document.getElementsByClassName('calculator');
var element = null;
for (var x = 0; x < as.length; x++) {
if (as[x].getAttribute('onclick') == 'add(number2,number3)') {
element = as[x];
break;
}
}
http://jsbin.com/feyaheji/1/edit?html,console
document.querySelector is the holy grail of finding elements in the DOM:
HTML:
<a class = "calculator" onclick = "add(number1,number2);">First</>
<a class = "calculator" onclick = "add(number2, number3);">Second</>
JavaScript:
var d2 = document.querySelector('.calculator[onclick*=number2][onclick*=number3]');
var d1 = document.querySelector('.calculator[onclick*=number1][onclick*=number2]');
console.log('Second', d2);
console.log('First', d1);
Notice the [onclick*=number2] selector which matches elements with the attribute name onclick and the value containing number2

How to open a specific URL onclick? [duplicate]

This question already has answers here:
Adding an onclick function to go to url in JavaScript?
(9 answers)
Closed 9 years ago.
I want to open a URL when the following is clicked:
<span class="taglib-text">Forgot Password</span>
Can anybody provide me with its Javascript?
Actually, I cannot control the HTML that's why I need to call an event using Javascript and class name i.e. taglib-text
Try this:
var url = 'http://www.google.com';
var element = document.getElementsByClassName('taglib-text')[0]; // only targets the first element it finds
element.addEventListener('click',function(){
location.href = url;
});
If you have many elements with that class you can instead use:
var url = 'http://www.google.com';
var elements = document.getElementsByClassName('taglib-text');
for (var i = 0; i < elements.length; i++){
elements[i].addEventListener('click', function () {
location.href = url;
});
}
FIDDLE
I changed my answer from using .querySelector() to .getElementsByClassName() because of Shawn's comment and this test

How to retrieve all td where the id begin by td_ in javascript [duplicate]

This question already has answers here:
getElementById() wildcard
(6 answers)
Closed 9 years ago.
I need your help :) !
I have a page where there are a lot of tags and I have to retrieve in an array all id who begin by td_
I can not use the jQuery framework... Else there will be more easy...
Do you how I can do it ?
You can use the querySelector:
elementList = document.querySelectorAll('td[id^=td_]');
DEMO
var nodeList = document.querySelectorAll('[id^=td_]'); // or if only TDs are tergated use: 'td[id^=td_]' instead {thx Derek}
var arr = []; // Will hold the array of Node's
for (var i = 0, ll = nodeList.length; i < ll; arr.push(nodeList[i++]));

Categories

Resources