我的 slider 中有以下代码。它与 CMS 配合使用,因此我需要使用 javascript 来到达该幻灯片内的第一个和第二个 p。所以我可以将类: mx-auto 和 text-truncate 添加到这些 p 中。 但我无法获得将这些类插入到 p 中的代码。
只是为了弄清楚为什么我无法手动添加类。 CMS 以编程方式添加 P,因此我无法更改它。
我使用 bootstrap 4.0 作为我的 slider 。
<div class="carousel-item">
<img class="d-block w-100" src="/Nieuwbouw/upload/images/banner1_1.png" alt="House 1">
<div class="carousel-caption mx-auto d-none d-md-block">
<h3 class="mx-auto">This is the title</h3>
<span class="caption-text1">
<p>This is the subtitel <-- TARGET THIS --></p>
</span>
<span class="caption-text2">
<p>This is all text! <-- AND THIS --></p>
</span>
<h3 class="mx-auto">From €256.000,-</h3>
<a href="#">+ see more</a>
</div>
</div>
我尝试了以下代码的多种变体,但没有任何效果(没有插入类)
var targetElement1 = document.getElementsByClassName(".caption-text1").getElementsByTagName("p")[0];
targetElement1.classList.add('mx-auto', 'text-truncate');
最佳答案
使用querySelectorAll
尝试以下方式:
var pElement = document.querySelectorAll('.carousel-item span > p');
pElement.forEach(function(p){
p.setAttribute('class','mx-auto text-truncate');
console.log(p);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-item">
<img class="d-block w-100" src="/Nieuwbouw/upload/images/banner1_1.png" alt="House 1">
<div class="carousel-caption mx-auto d-none d-md-block">
<h3 class="mx-auto">This is the title</h3>
<span class="caption-text1">
<p>This is the subtitel <-- TARGET THIS --></p>
</span>
<span class="caption-text2">
<p>This is all text! <-- AND THIS --></p>
</span>
<h3 class="mx-auto">From €256.000,-</h3>
<a href="#">+ see more</a>
</div>
</div>
关于javascript - 使用 Javascript .getElement 在类内定位 P,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592525/