Im a Javascript beginner. I want to get attribute value on multiple class elements. I tried with IDs, but it's not revelent since IDs are supposed to be unique.
My HTML looks like this :
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_1">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_2">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_3">
Any help would be appreciated.
Thanks
First close your anchor Tags
Test1
Test2
Test3
then use this javascript function
function myJavascriptFunc(item)
{
alert(item.getAttribute("data"));
return false
}
and let me know if it works
Trying using this:
function test(){
var x = document.getElementsByClassName("myClass");
var i;
for (i = 0; i < x.length; i++) {
var val = x[i].innerHTML; //innerHTML returns the written text inside the element tag
alert(val);
alert(x[i].getAttribute("data")); //this will give you the data attribute
}
}
You can get any other attribute you like from that element just by replacing the innerHTML by that attribute's name
I'm too late as always, but I would use the HTML 5 dataset attribute:
<!DOCTYPE html>
<html>
<head>
<script>
function doSomething(classname,func,datakey)
{
var hrefs = document.getElementsByClassName(classname), // get all elements with the class
i = 0; // initialize the loop
for(;i < hrefs.length; i++) // iterate through all elements
{
func(hrefs[i].dataset[datakey]); // execute the passed function with the content of the dataset as first argument
}
}
function alertval(value) // example function to do something with it
{
alert(value);
}
window.onload = function ()
{
doSomething("Test",alertval,"something"); // just test it
}
</script>
</head>
<body>
Test1
Test2
Test3
</body>
</html>
You are probably wondering why you can't just reach the data attribute using the this keyword from myJavascriptFunc(). That's because you are using inline event registration, and the this keyword then refers to the window object. To get around this you must make sure the this keyword is actually written into the onclick property.
var elems = document.getElementsByClassName('test');
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = myJavascriptFunc;
}
function myJavascriptFunc() {
alert(this.getAttribute('data'));
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
FooBar_One<br>
FooBar_Two<br>
FooBar_Three
</body>
</html>
A way to see the difference:
<element onclick="myJavascriptFunc()">. // this refers to the window object as the element does not get passed along.
<element onclick="alert(this.getAttribute('data'));">. // this refers to the element.
Related
I would like to set id attributes for all the DOM elements by default. The IMPORTANT point is that it should happen during the construction of elements (when the browser is parsing HTML code and creating HTML elements and before appending them to the DOM tree). For example, if the HTML code of my website is like this:
<html>
<head>
<script>
//overriding constructor of Element
</script>
</head>
<body>
<p id='nH6Rf72Jk'> This is a paragraph </p>
<p> This is another paragraph </p>
</body>
</html>
I would like to have an id attribute (a random value) even for elements that do not explicitly an id has specified for them. I think it might be possible by overriding constructor of the Element interface (by the script that exists in the head). In other words, while browser is generating the elements and appending them to the DOM tree, check the id attribute; if it doesn't exist, generate a random value and set it as the id. Does anyone know if is possible to override the Element constructor? Or is there any other solution for this problem?
This should work
let all = document.getElementsByTagName("*");
for (let i=0; i < all.length; i++) {
if(all[i].getAttribute('id') === null){
all[i].setAttribute('id', makeId(6));
}
}
function makeId(length) {
let finalStr = '';
let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charsLength = chars.length;
for (i = 0; i < length; i++ ) {
finalStr += chars.charAt(Math.floor(Math.random() * charsLength));
}
return finalStr;
}
document.addEventListener('DOMContentLoaded', () => {
let elements = document.querySelectorAll('body *');
elements.forEach((elem => {
if (!elem.getAttribute('id')) {
elem.setAttribute('id', btoa(window.crypto.getRandomValues(new Uint32Array(1))[0]));
}
}));
});
I would like to make some javascript code that once run adds a title of each link that is the title of the page it leads to. Sorry, all I can figure out is...
<body onload="replace()">
<script>
function replace() {
document.getElementsByTagName("a").title=this.href;
}
</script>
hi
hi2
hi3
</body>
But nothing happens and I can't figure it out.
more simple, just place correctly your script:
<body>
hi
hi2
hi3
<!-- Script for everything, just placed before </body>-->
<script>
document.querySelectorAll('a').forEach(A=>{ A.title = A.href })
</script>
</body>
getElementsByTagName returns a collection of elements, you need to use loop for setting whatever to each link.
<body onload="replace()">
<script>
function replace() {
// find all links
var links = document.getElementsByTagName("a");
// loop the collection and set title to each one
for (var i = 0; i < links.length; i++) {
links[i].title = links[i].href;
}
}
</script>
hi
hi2
hi3
</body>
Afaik, there is no way to detect a page title from a different page in JS. If you know the titles in advance, you can create a mapping object and loop over your links like so:
var map = [['link','title'],['link','title']];
$('a').each(function() {
for(var i=0; i<map.length; i++) {
if(map[i][0] == $(this).attr('src'))
$(this).attr('title', map[i][1]);
}
});
That should set all your links with the appropriate page titles based on matching the src attributes of each link against the link in your mapping object
You can use window.location.href instead of this.href. Also, you probably need to run through each link in the tag list:
function start() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].title = window.location.href;
}
}
window.load = start();
hi
hi2
hi3
Try this answer, I have tried to add comments so that you could understand what has happened:
<a class="link" href="about.html">About</a>
<a class="link" href="careers.html">Careers</a>
<a class="link" href="contact.html">Contact</a>
<script>
//create a true array
var links = Array.from(document.getElementsByTagName("a"));
window.addEventListener(
"load", //Trigger Load event of window object
()=> //return this function
{
//links is an array of a-tag objects
for (let i = 0; i < links.length; i++)
{
//for each a tag object
//set the attribute targeted below
links[i].setAttribute
(
//target the title attribute
"title",
//set it to the current href attribute value of the that a-tag object
links[i].getAttribute("href")
);
}
}
);
</script>
When I try to dynamically fill a wrapper element with HTML elements, and then add an EventListener for that element, it only uses the last value.
window.onload=function(){
sW="";
for(var i = 0; i < 5; i++) {
var e = document.createElement('div');
e.innerHTML = "test div number "+i;
e.addEventListener('click', function() {alert("t:"+i);});
document.getElementById('wrap').appendChild(e);
}
}
<html>
<body>
<div id="wrap"></div>
</body>
</html>
That's because var keeps the the reference to the variable. Use let instead.
I’m getting an ".addEventListener is not a function" error. I am stuck on this:
var comment = document.getElementsByClassName("button");
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield">
</div>
The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.
So you should move your script after the html element is available.
Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following
comment[0].addEventListener('click' , showComment , false ) ;
If you want to add event listener to all the elements, then you will need to loop through them
for (var i = 0 ; i < comment.length; i++) {
comment[i].addEventListener('click' , showComment , false ) ;
}
document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.
Update #1:
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
Update #2: (with removeEventListener incorporated as well)
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment(e) {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
for (var i = 0; i < numComments; i++) {
comments[i].removeEventListener('click', showComment, false);
}
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
var comment = document.getElementsByClassName("button");
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i in comment) {
comment[i].onclick = function() {
showComment();
};
}
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield"></div>
The first line of your code returns an array and assigns it to the var comment, when what you want is an element assigned to the var comment...
var comment = document.getElementsByClassName("button");
So you are trying to use the method addEventListener() on the array when you need to use the method addEventListener() on the actual element within the array. You need to return an element not an array by accessing the element within the array so the var comment itself is assigned an element not an array.
Change...
var comment = document.getElementsByClassName("button");
to...
var comment = document.getElementsByClassName("button")[0];
Another important thing you need to note with ".addEventListener is not a function" error is that the error might be coming a result of assigning it a wrong object eg consider
let myImages = ['images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg'];
let i = 0;
while(i < myImages.length){
const newImage = document.createElement('img');
newImage.setAttribute('src',myImages[i]);
thumbBar.appendChild(newImage);
//Code just below will bring the said error
myImages[i].addEventListener('click',fullImage);
//Code just below execute properly
newImage.addEventListener('click',fullImage);
i++;
}
In the code Above I am basically assigning images to a div element in my html dynamically using javascript. I've done this by writing the images in an array and looping them through a while loop and adding all of them to the div element.
I've then added a click event listener for all images.
The code "myImages[i].addEventListener('click',fullImage);" will give you an error of "addEventListener is not a function" because I am chaining an addEventListener to an array object which does not have the addEventListener() function.
However for the code "newImage.addEventListener('click',fullImage);" it executes properly because the newImage object has access the function addEventListener() while the array object does not.
For more clarification follow the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function
The main reason of this error is this line
document.getElementsByClassName("button")
Cause the getElementsByClassName returns an array-like object of all child elements or a collection of elements.
There are two possible solutions AFAIK -
Treat the variable containing document.getElementsByClassName("button") as an array and be specific when using an event listener.
Example -
comment[0].addEventListener('click' , showComment , false )
Use id for selecting that specific element.
Example-
document.getElementById('button')
Try this one:
var comment = document.querySelector("button");
function showComment() {
var place = document.querySelector('#textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
Use querySelector instead of className
<script src="main.js" defer></script>
which makes execute your code after the document fully loaded hence the javascript has complete reference
<a href='http://example.com'>Goes To Example.com</a>
I want to get the href value of this. This link will always be on the page
I will usually do something like: document.getElementsByTagName('a')[5]. However, the number of links are always changing so it isn't reliable at all. Is there a way I can get it by the text Goes To Example.com?
As you said in comment you can use jquery, use Contains like bellow
$('a:contains("Goes To Example.com")')
DEMO
Use the JQuery :contains() selector. You can then get the attribute "href", as follows:
$("a:contains(Goes To Example.com)").attr("href");
For example, the following snippet will popup an alert with http://example.com inside it:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<a href='http://example.com'>Goes To Example.com</a>
<script>
alert($("a:contains(Goes To Example.com)").attr("href"));
</script>
</body>
</html>
You could use xpath:
document.evaluate(
'/html/body//a[text()='Goes To Example.com']/#href',
document, null, XPathResult.ANY_TYPE, null);
You can iterate over the result (which is of type XPathResult) using iterateNext.
See xpath documentation for details: https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate.
You can do document.getElementById and give the id to the a tag. To get the text you can use innerHTML function
Working Fiddle
HTML Markup
<a id="test" href='http://example.com'>Goes To Example.com</a>
JS:
document.getElementById("test").innerHTML
If you want it by href attribute only then you have to loop it over
var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === 'http://www.example.com/') {
alert(el.innerHTML);
}
}
You can do it like this:
var links = document.getElementsByTagName('a');
var requiredId = "";
for(var i=0; i<links.length; i++){
if(links[i].innerHTML == "Goes To Example.com"){
requiredId = links[i].getAttribute('id');
}
}