如何通过javascript获取span值。
document.getElementsByClassName("breadcrumb-item")[1]
我想要得到跨度的值。如何使用javascript获得它。
<li class="breadcrumb-item">
<a href="@crumbUrl">
<span>
@Html.Raw(breadcrumb.Name)
</span>
</a>
</li>
您可以这样使用querySelector
:
console.log(document.querySelector('.breadcrumb-item > a > span').innerHTML);
<ul>
<li class="breadcrumb-item">
<a href="@crumbUrl">
<span>
value <!--@Html.Raw(breadcrumb.Name)-->
</span>
</a>
</li>
</ul>
参考:
- Document.querySelector ()
If大于1
document.querySelectorAll('.breadcrumb-item > a > span').forEach(el =>{
console.log(el.innerHTML);
});
<ul>
<li class="breadcrumb-item">
<a href="@crumbUrl">
<span>
value <!--@Html.Raw(breadcrumb.Name)-->
</span>
</a>
</li>
<li class="breadcrumb-item">
<a href="@crumbUrl">
<span>
value2 <!--@Html.Raw(breadcrumb.Name)-->
</span>
</a>
</li>
</ul>
参考:
- Document.querySelectorAll ()
- Array.prototype.forEach ()
您可以创建一个变量来获取元素:
var list = document.getElementsByClassName("breadcrumb-item"[0];
var spanVal = list.getElementsByTagName("span")[0].innerHTML;
console.log (spanVal);