Home > OS >  How do I get a special value information from a <strong>-class?
How do I get a special value information from a <strong>-class?

Time:01-04

I am trying to extract the data-group-id-value from the strong written class in the given menu vis_item. The HTML code looks like that:

<div  align="center">
<a  data-group-id="0" data-group-type="all" href="#" data-title="">1</a>
<strong  data-group-id="1234567" data-group-type="static" data-title="">2</strong>
<a   [.....] </a>
</div>

I used the following lines:

var group_menu = document.getElementsByClassName("vis_item"); //Get Menu-Class
var active_group_class = group_menu.innerHTML("strong"); // Get Active Menu Point
var active_group_id = active_group_class.data-group-id; // extra data-group-id Value

What I am I doing wrong?

CodePudding user response:

There's a few things wrong with your js

  • getElementsByClassName returns an array
  • there's no such function as innerHTML()
  • to get the data attribute value, you need to use dataset

var group_menus = document.getElementsByClassName("vis_item"); // first vis items

Array.from(group_menus).forEach(group_menu => {                // loop through vis items
  var active_group_class = group_menu.querySelector("strong"); // Get strong tag
  var active_group_id = active_group_class.dataset.groupId;    // get data-group-id Value

  console.log(active_group_id)
})
<div  align="center">
  <a  data-group-id="0" data-group-type="all" href="#" data-title="">1</a>
  <strong  data-group-id="1234567" data-group-type="static" data-title="">2</strong>
  <a  [.....] </a>
</div>

CodePudding user response:

You access data items from the element’s dataset attribute like the following:

let active_group_id = active_group_class.dataset.groupId

Also, innerHTML doesn’t work like you’re using it - https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Your question isn’t really clear on how you’re using the code so I wouldn’t be able to suggest an alternative but you will need to select the element using something like this if based on an onclick or click event or you could loop through the parent element’s children to find the strong.

It’s also a bit unclear why you have one strong amongst a load of anchor tags.

  • Related