如何用jQuery将元素文本替换为元素title属性值?
Solution
To replace the text content of every .timeago element with its own title attribute value, you need to process each element individually. Your current code fails because $('.timeago').text() returns the combined text of all matched elements, not the text of each specific element.
jQuery Implementation
Use the .each() method to loop through each .timeago element. For each element, retrieve its title attribute and set it as the new text content:
$('.timeago').each(function() { const titleText = $(this).attr('title'); $(this).text(titleText); });
Vanilla JavaScript Alternative
If you prefer not to use jQuery, here's the equivalent vanilla JS code:
document.querySelectorAll('.timeago').forEach(element => { const titleText = element.getAttribute('title'); element.textContent = titleText; });
Example Result
For your sample element:
<abbr class="timeago" data-datetime="2022-10-30T18:54:39Z" title="10/30/2022 11:54 AM">15 days ago</abbr>
After running the code, it will become:
<abbr class="timeago" data-datetime="2022-10-30T18:54:39Z" title="10/30/2022 11:54 AM">10/30/2022 11:54 AM</abbr>
内容的提问来源于stack exchange,提问作者bstime
相关产品推荐
相关产品推荐

