简体   繁体   English

如何获取跨度 class 中的所有标签 innerHTML

[英]How to get all a tag innerHTML in a span class

<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我如何获得所有 a 标签内部 html 之类的

Action Adventure Apocalypse Fantsay Magic动作 冒险 启示录 奇幻 魔法

I tried using document.querySelector(".mgen a").innerHTML , but I am only getting first a tag innerHTML.我尝试使用document.querySelector(".mgen a").innerHTML ,但我只得到第一个标签 innerHTML。 I don't want to use loop to get all innerHTML as it would be lengthy.我不想使用循环来获取所有 innerHTML,因为它会很长。

We can try getting the textContent of the .mgen element.我们可以尝试获取.mgen元素的textContent 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如果你希望它在同一行中,单词之间只有一个空格,我们可以使用正则表达式删除newline和其他空格,并将它们替换为space

console.log(document.querySelector(".mgen").textContent.replace(/\s/g, ' '))

Use the .innerText property on the targeted element.在目标元素上使用.innerText属性。 .innerText() represents the rendered text content of a node and its descendants. .innerText()表示节点及其后代的渲染文本内容。

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.您还可以使用textContent属性。 They work similar with few differences .它们的工作方式相似, 差别不大

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM