How to get Item's attributes and store it in a variable using JavaScript?

Hello Programmer, Good day, I need to store id’s value like var item=“item-12345”; when I will click on any item link. Suppose if i click on item 1 then my code will store “item-12345” in a variable and if click on other link variable will be changed and will be stored new id’s value.

https://jsfiddle.net/9ro3c7f2/1/

1 Like

You need to use Jquery

How to do that ? any solution will be appreciated.

You don’t need to use jquery, but jquery is helpful with DOM stuff. You will want to research event listeners.

We aren’t going to write the code for you.

You might try looking up something like jquery .onclick()

Which you can use to assign a value to a variable.

I’m not really sure what you are trying to accomplish, but I would start by learning something like jquery. You can’t build a house without tools.

Hi @masumluf

// select all `a` links 
var links = document.querySelectorAll("a")
var item
// TODO :
// loop all the links 
// and add an `eventListener` on `click` to each item

i dont want to give all the solution , just try to solve the problem know

failed , just did it https://jsfiddle.net/masumxn/9ro3c7f2/39/

1 Like

What attribute are you trying to log? You are logging the class name (each letter in the class name and then the full class name for each click).

document.getElementById(".view");

  1. You do not have an #view id.

  2. If you did have a #view id it would be document.getElementById("view"); (no .)

  3. You are not using item for anything.

Hi Guys, this is my solution:

var item = "";
// selection of all the a elements
document.querySelectorAll('a').forEach(
	link => {
        // attach event listener on click for any elements
  	    link.addEventListener('click', () => {
    	item = link.getAttribute('id')
    })
});

Happy Coding :slight_smile:

This will not work on older browsers.

Hi Randell

What versions of browser do you mean by older?
Usually I verify any method on the CanIUse website.

The forEach ES5 method is supported in the 98.86% of the browsers while the quertSelectorAll si supported for the 99% :slight_smile:

IE11 does not support using the forEach with querySelectorAll. IE11 also does not support arrow function syntax.

Just to be clear it is the forEach on a NodeList that is being referred to. Not forEach on an array or just using querySelectorAll.

querySelectorAll returns a NodeList, but using forEach on it in IE 11 does not work.

I know it does. I just wanted to make it clear that both forEach and querySelectorAll does work in IE 11. But that forEach on a NodeList does not work.

2 Likes

A way to support IE11 (if that is important to anyone) using @lucatardi’s suggested code is to:

list = Array.prototype.slice.call(document.querySelectorAll('a'));
list.forEach(
  link => {
    .
    .
  })
});

I’ve done using for loop and forEach, i hope it will be work. Thank you everybody :slight_smile:

1 Like