<span class="mgen">
<a rel="tag">Action</a>
<a rel="tag">Adventure</a>
<a rel="tag">Apocalypse</a>
<a rel="tag">Fantasy</a>
<a rel="tag">Magic</a>
</span>
How do I get all the a tag inner html like
Action Adventure Apocalypse Fantsay Magic
I tried using document.querySelector(".mgen a").innerHTML, but I am only getting first a tag innerHTML. I don't want to use loop to get all innerHTML as it would be lengthy.
We can try getting the textContent of the .mgen element. This would return only the text content of the inner elements.
console.log(document.querySelector(".mgen").textContent)
<span class="mgen">
<a rel="tag">Action</a>
<a rel="tag">Adventure</a>
<a rel="tag">Apocalypse</a>
<a rel="tag">Fantasy</a>
<a rel="tag">Magic</a>
</span>
If you want it in the same line with only one space between the words, we can remove the newline and other spacing using regex and replace them with space
console.log(document.querySelector(".mgen").textContent.replace(/\s/g, ' '))
Use the .innerText property on the targeted element. .innerText() represents the rendered text content of a node and its descendants.
Try this:
<body>
<span class="mgen">
<a rel="tag">Action</a>
<a rel="tag">Adventure</a>
<a rel="tag">Apocalypse</a>
<a rel="tag">Fantasy</a>
<a rel="tag">Magic</a>
</span>
<script>
let element = document.querySelector(".mgen")
console.log(element.innerText)
</script>
</body>
You can also use textContent property. They work similar with few differences.