将innerHTML替换为具有类的每个元素的属性值

时间:2016-01-26 01:44:57

标签: javascript dom

请考虑此HTML:

<a class="title" threedots="Product Name 1"></a>
<a class="title" threedots="Product Name 2"></a>
<a class="title" threedots="Product Name 3"></a>

我想将其更改为:

<a class="title" threedots="Product Name 1">Product Name 1</a>
<a class="title" threedots="Product Name 2">Product Name 2</a>
<a class="title" threedots="Product Name 3">Product Name 3</a>

使用JavaScript或jQuery。我只能用这个来改变第一次出现:

var fullName = document.getElementsByClassName("title")[0].getAttribute("threedots");
document.getElementsByClassName("title")[0].innerHTML = fullName;

但我需要帮助编写一个可以改变所有事件的脚本。我研究过foreach和HTMLcollection,但我不理解它们。有人能指出我正确的方向来编写一个脚本,找到每个<a class="title">并获取其threedots属性的值并将其注入吗?

3 个答案:

答案 0 :(得分:2)

您只需按[threedots]属性和类名选择所有元素,然后使用简单的for循环迭代它们:

var elements = document.querySelectorAll('.title[threedots]');
for (var i = 0; i < elements.length; i++) {
  elements[i].textContent = elements[i].getAttribute('threedots');
}

或使用.forEach()

var elements = document.querySelectorAll('.title[threedots]');
Array.prototype.forEach.call(elements, function (el) {
  el.textContent = el.getAttribute('threedots');
});

作为旁注,由于您只是在更改文字,因此您可以使用.textContent property而不是.innerHTML。此外,threedots不是有效属性。请考虑使用data-*属性,例如data-threedots

<a class="title" data-threedots="Product Name 1"></a>
<a class="title" data-threedots="Product Name 2"></a>
<a class="title" data-threedots="Product Name 3"></a>

然后您可以访问属性.dataset.threedots

var elements = document.querySelectorAll('.title[data-threedots]');
for (var i = 0; i < elements.length; i++) {
  elements[i].textContent = elements[i].dataset.threedots;
}

由于您提到了jQuery,您还可以使用以下内容:

$('.title[data-threedots]').text(function () {
  return $(this).attr('data-threedots');
});

答案 1 :(得分:1)

因此,我们可以迭代它而不是仅使用document.getElementsByClassName(“title”)的第一个索引。

ggplot(dat, aes(x = xvar, y = yvar)) +
  geom_point(shape=20, size=1) +
  segments(xvar[start], yvar[start], xvar[end], xvar[end], col = 'blue')
var titles = document.getElementsByClassName("title");

for(var i = 0; i < titles.length; i++) {
  
  var title = titles[i];
  
  title.innerHTML = title.getAttribute("threedots");
}
a {
  display: block;
}

答案 2 :(得分:0)

使用jQuery选择所有锚元素并进行设置。

&#13;
&#13;
$('a').each(function(){
  $(this).html($(this).attr('threedots'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="title" threedots="Product Name 1"></a>
<a class="title" threedots="Product Name 2"></a>
<a class="title" threedots="Product Name 3"></a>
&#13;
&#13;
&#13;