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:
- Get all of the
<div>
s (selector isdiv.text1
) - 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>