I want to add a CSS styling class to all instances of a selective set of elements: for example, all p elements as well as all h4 elements.
I define two JS variables which get all elements of the aforementioned tags, and insert them into an array, so that I can make a function which, in theory, should apply the selected class to all instances of the selected elements/tags.
However, when I run the code, it seems that the function assigns the class only to the first item of the array.
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.italic { font-style: italic; }
</style>
</head>
<body>
<h4>Text goes in here</h4>
<p>Text goes in here</p>
<script>
function styleTxt() {
let h4Elems = document.getElementsByTagName("H4");
let pElems = document.getElementsByTagName("P");
const elemArray = [pElems, h4Elems];
for (eachElem in elemArray) {
let elemInsts = elemArray[eachElem];
for (eachInst in elemInsts) {
let givenInst = elemInsts[eachInst];
givenInst.classList.add("italic");
}
}
}
styleTxt();
</script>
</body>
</html>
If I invert the order of the element tags inside the array, then the h4 element will get the .italic class but the p element will not.
Perhaps it is not possible to use the "document" directive twice? Is there an alternative method to automatically add the same class to a set of multiple (but not all) html tags?
