Home > Back-end >  how to get value from DOMTokenList
how to get value from DOMTokenList

Time:01-19

I have DOMTokenList in console.log()

let tag = document.getElementsByTagName('body')[0];
let list = tag.classList;
console.log(list);

View from Console:

DOMTokenList []
0: "Konop_1"
length: 1
value: "Konop_1"
<prototype>: DOMTokenListPrototype { item: item(), contains: contains(), add: add(), … }

enter image description here

How I can get only value?

console.log(list.value); //-> empty string

CodePudding user response:

DOMTokenList is not traited as an array but you can force javascript to consider it like an Array by using the Array.from

let tag = document.getElementsByTagName('h2')[0];
let classes = Array.from(tag.classList);

console.log(classes);
<h2 >Title</h2>
<h2 >Title</h2>

As you will have list of all classes contains in the tag.classList property as an Array you can do whatever you want

CodePudding user response:

If you just have one value or would like to return the entire value of the class attribute you can use the property className:

let tag = document.getElementsByTagName('body')[0];
console.log(tag.className);
<body ></body>

If there are more values you can use the classList, but you need to either look for a specific one or iterate the list:

let tag = document.getElementsByTagName('body')[0];
let list = tag.classList;

if(list.contains('Konop_1')){
  console.log('has "Konop_1"');
}

list.forEach(item => {
  console.log(item);
});
<body ></body>

  •  Tags:  
  • Related