Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS Function to change title of html div based on the textContent

I’m trying to have js change the title attributes for each div based on each divs text content in html.

I want to add the title of each div from its own text, so for example: "Text Example 1"s title would be "Text Example 1", "Text Example 2"s title would be "Text Example 2" and so on.

Currently I’ve made a js code that does that but only for one of the divs. I’m a complete beginner in js so any advice is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="example">
<div class="text1" id="id-text1">Text Example 1</div>
</div>

<div class="example">
<div class="text1" id="id-text1">Text Example 2</div>
</div>

<div class="example">
<div class="text1" id="id-text1">Text Example 3</div>
</div>
const titleContent = document.getElementById("id-text1");

function ChangeTitle(){
document.querySelectorAll('.text1').forEach(function ChangeTitleSecond(){
titleContent.setAttribute('title', titleContent.textContent);
})
};

window.onload = ChangeTitle();

>Solution :

Steps to set title of <div> to it’s (text) content:

  1. Get all of the <div>s (selector is div.text1)
  2. For each of them, set title to innerText value

Solution:

<div class="example">
  <div class="text1">Text Example 1</div>
</div>
<div class="example">
  <div class="text1">Text Example 2</div>
</div>
<div class="example">
  <div class="text1">Text Example 3</div>
</div>
<script>
divs = Array.from(document.querySelectorAll("div.text1"))

for (elem of divs) {
  elem.setAttribute("title", elem.innerText)
}
</script>

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading