Javascript获取没有HTML标记的DIV值

时间:2018-02-07 19:22:00

标签: javascript html

我正在为div分配值" AMD"," APPLE"。

<div id="company"></div>

但是,当我调用 outputStock()时,我的警报值会显示 HTML标记。如何获取我指定的当前字符串值?

<script>
    var company = ["AMD", "APPLE"];
    company.forEach(function(i) {
        document.getElementById("company").innerHTML+= "<p>" + i + "</p>";
    });
</script>
<script>
    function outputStock() {
        var stockname = document.getElementById("company").innerHTML;
        alert(stockname);
    }
</script>

UPDATE *:当我输出alert()时,我得

<p>AMD</p><br><hr><p>APPLE</p><br><hr>

如何摆脱警报中的html标签并获取字符串? 像这样的东西?

document.getElementById("company").innerHTML = html.replace(/<[^>]*>/g, "");

2 个答案:

答案 0 :(得分:2)

<script>
    var company = ["AMD", "APPLE"];
    company.forEach(function(i) {
        document.getElementById("company").innerHTML += "<p>" + i + "</p><br />" + "<hr>";
     });
</script>      
<script>
     function outputStock() {
         var name = document.getElementById("company").innerHTML;
         alert(name);
     } 
</script>
  

Div标签没有任何属性,例如值。要从div标签中检索任何值,您必须使用.innerHTML

答案 1 :(得分:1)

divs内容是innerHTML而不是值,如果你改变它将返回AMD和APPLE。

&#13;
&#13;
var company = ["AMD", "APPLE"];
company.forEach(function(i) {
document.getElementById("company").innerHTML+= "<p>" + i + "</p>";
});



var name = document.getElementById("company").innerHTML
var noTags = name.replace('<p>' , ' ').replace('</p>' , ' ').replace('<p>' , ' ').replace('</p>' , ' ')
alert(noTags)
&#13;
<div id="company"></div>
&#13;
&#13;
&#13;