Note: As getElementS
states, getElementsByClassName
returns an array like HTMLCollection.
So inorder to access the first element (your class inline-keyword-marker
), you need to add [0]
to your method like this:
document.getElementsByClassName('inline-keyword-marker')[0]
function myFunction() {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker")[0].innerHTML;
}
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
You might also to read this. It explains your issue more detailed than I did.
To handle all your classes, you can use this method:
function myFunction() {
var classes = document.getElementsByClassName('inline-keyword-marker'); // Get all elements
var myDiv = document.getElementById('mydiv'); // Get the div for the result
myDiv.innerHTML = ""; // At first, we clear the result div; not neccessary, just for the optic
// Because we got a HTMLCollection back, we need to loop through it
for (var i = 0; i < classes.length; i++) {
myDiv.innerHTML += classes[i].innerHTML + "<br>"; // With [i] we access every element -> at first the first one, then the second on and so on
// I also added a <br> tag, so the results get append beneath each other, not next to each other
}
}
<span class="inline-keyword-marker valid">Product1</span>
<span class="inline-keyword-marker valid">Product2</span>
<span class="inline-keyword-marker valid">Product3</span>
<span class="inline-keyword-marker valid">Product4</span>
<span class="inline-keyword-marker valid">Product5</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>