Ok so after tinkering some more and going through about a zillion different websites with really unclear and difficult to follow explanations I’ve discovered that getting the parent data attribute is actually pretty simple all you need to do is this
Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div data-name="test_data_attribute">
<div>
<button onclick="send(closest('[data-name]'))">alert data attribute</button>
</div>
</div>
<script>
function send(parent)
{
alert(parent.dataset.name);
}
</script>
</body>
</html>
This will loop up the dom till it finds a data attribute with a matching name and then send that into the function I can then access the value inside with the dataset property followed by the name of the data attribute.
I also learned that when accessing the data attribute the name must be in camel case so if my data attribute was called
Then to send it and access it I would do
Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div data-user-name="test_data_attribute">
<div>
<button onclick="send(closest('[data-user-name]'))">alert data attribute</button>
</div>
</div>
<script>
function send(parent)
{
alert(parent.dataset.userName);
}
</script>
</body>
</html>
I also learned that if you trying to get a class but the class contains more then 1 value then the example in the opening post wont work as it will return both class values so if you only want to access 1 of them then instead of using .className to access the value what you need to do is use .classList followed by the index value of the class name you want to access.
So if you want to access just the first value then the index value would be [0] for the second value the index value would be [1] for the third value the index value would be [2] and so on
for example here I'm getting the second of 3 class names "test_class_2"
Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div class="test_class_1 test_class_2 test_class_3">
<div>
<button onclick="send(closest('.test_class_2'))">alert class</button>
</div>
</div>
<script>
function send(parent)
{
alert(parent.classList[1]);
}
</script>
</body>
</html>
While this might not seem very exciting I figure I’ll leave it here for the benefit of anyone else that is learning JavaScript and trying to get the parent id, parent class or parent data attribute, since this sort of thing is a pretty fundamental task which really isn't that well explained on most websites.