I'm working on a simple problem that asked me to add an onclick command and fire the function I did it but now I want to see if I can do it with an evenListener. Turns out I can't. can someone tell me what I'm doing wrong?
<body>
<p><a id="w3r" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="https://www.w3resource.com/">w3resource</a></p>
<button >Click here to get attributes value</button>
</body></html>
function getAttributes() {
var v = document.getElementById('w3r').href ;
alert('the value of the attrbibute is : '+v);
var w = document.getElementById('w3r').hreflang;
alert('the value of the attrbibute is : '+w);
var x = document.getElementById('w3r').rel;
alert('the value of the attrbibute is : '+x);
var y = document.getElementById('w3r').target;
alert('the value of the attrbibute is : '+y);
var z = document.getElementById('w3r').type;
alert('the value of the attrbibute is : '+z);
document.getElementsByTagName('P')[0].addEventListener('click' , getAttributes());
}
You may find querySelector
easier to use.
getAttributes()
assigns the result of calling the function to the listener rather than assigning the reference to the function which will be called when the listener is fired: addEventListener('click', getAttributes);
.
Your listener is inside the function. It should be outside the function otherwise it will never get called.
It looks like you want the click listener to be on the button, and not the paragraph element.
You can save on repetition by iterating over the element attributes.
function getAttributes() {
const el = document.querySelector('#w3r');
if (el.hasAttributes()) {
Array.from(el.attributes).forEach(attr => {
console.log(`The value of ${attr.name} is ${attr.value}`);
});
}
}
const button = document.querySelector('button');
button.addEventListener('click', getAttributes);
<p><a id="w3r" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="https://www.w3resource.com/">w3resource</a></p>
<button>Click here to get attributes value</button>
Additional documentation
First the eventListener is inside the function.
Second in getElementsByTagName
you put P (uppercase), that's work if you put p (lowercase)
Mistake is that you are adding event listener in a function you are trying to call. So this mean it will not be added to your element until it is called from somewhere else (which will never happen in your case). Solution for this is to put line where you add event listener direcly into the script
tag
document.getElementsByTagName('P')[0].addEventListener('click' , getAttributes());
Just make sure that your script is at the end of the body
and not in the head
or beginning because page is loaded from top to bottom and if you put your script above your html it will not be able to get your element since it will not exist yet in the time it tries to get it.