javascript - 使用 Javascript .getElement 在类内定位 P

标签 javascript twitter-bootstrap

我的 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/

相关文章:

javascript - 可切换按钮不起作用

javascript - 自定义复选框在剑道网格中不可单击

html - 如何在多个 Twitter Bootstrap 选项卡上只有一个表单?

javascript - 平面 UI 复选框样式不起作用

html - 从 Bootstrap 中的表顶部删除行

javascript - 将 catch block 添加到 Promise 会返回待处理而不是被拒绝

javascript - 无法触发事件 "Uncaught ReferenceError: killMedia is not defined"

php - 不存储 POST 数据 (json)

javascript - 如何让这两个 "col"在手机上以不同的顺序堆叠? Bootstrap 4

javascript - 获取关闭模态的元素