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

Time:10-27

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.

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

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

<div >
<div  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();

CodePudding user response:

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 >
  <div >Text Example 1</div>
</div>
<div >
  <div >Text Example 2</div>
</div>
<div >
  <div >Text Example 3</div>
</div>
<script>
divs = Array.from(document.querySelectorAll("div.text1"))

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

Text Example 2
Text Example 3
<script> divs = Array.from(document.querySelectorAll("div.text1")) for (elem of divs) { elem.setAttribute("title", elem.innerText) } </script>" rel="nofollow noreferrer">Demo

CodePudding user response:

getElementById() returns only a single element. id attributes should be unique within the document. But that's ok, you don't need it. You're already getting a list of the elements to go through with querySelectorAll()

forEach() will pass each element as the first parameter of your function.

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

window.onload = ChangeTitle();

CodePudding user response:

You can use this implementation. If you need a list of some items which has the same attributes (such as id, class or tag) you can pick them all through their specific attribute of them by querySelectorAll.

const titleContentList = document.querySelectorAll('[id=id-text1]')

function ChangeTitle(){

titleContentList.forEach((item)=>{
const title = item.textContent

if(!title) return;

item.setAttribute('title',title)
})                   
  } 

window.onload = ChangeTitle();
  • Related