简体   繁体   中英

How can I add hover-over text to an existing web page in Javascript without using ID tags?

I am building a Chrome extension which I would like to eventually have several features to add enhancements to an existing web application. The first of those features will be to add some hover-over (aka tooltip or mouse over) text to certain elements of certain pages within an existing website. Unfortunately the places on the page where I want to add the text to don't have any specific ID tags to reference, so I figured I would replace unique parts of the text on the page.

So here is an example of the code of the original webpage:

<html>
<table>
<tr>
  <td>First Name</td>
  <td>Last Name</td>
</tr>
<tr>
  <td>John</td>
  <td>Smith</td>
</tr>
</table>
</html>

And this is what I want it to look like after Javascript adds in the hover-over text (I am open to the way the hover-over text is applied, as long as it has hover-over text...I know applying span title tags works in Chrome):

<html>
<table>
<tr>
  <td><span title="First Name of the student">First Name</span></td>
  <td><span title="Last Name of the student">Last Name</span></td>
</tr>
<tr>
  <td>John</td>
  <td>Smith</td>
</tr>
</table>
</html>

This is the Javascript that I have so far. It works, but is there a way to make it more efficient, or is there a better way to do this?

document.body.innerHTML = document.body.innerHTML
  .replace(/>First Name</g, '><span title="First Name of the student">First Name</span><')
  .replace(/>Last Name</g, '><span title="Last Name of the student">Last Name</span><');

Thank you in advance for your help, an thank you for the opportunity to rewrite my question for clarity.

You can create an object having properties that match current element text to be replaced, values containing text to set at title attribute; use .forEach() or for loop to iterate document.body.childNodes ; Object.hasOwnProperty() to check for matched text content of node, Node.replaceChild() to replace the node

 var re = { "Stu#": "Student Number", "Last Name": "Student Last Name", "First Name": "First Name of the student" }; document.body.childNodes .forEach(function(el) { var text = (el.nodeValue || el.textContent).trim(); if(re.hasOwnProperty(text)) { var span = document.createElement("span"); span.textContent = text; span.setAttribute("title", re[text]); el.parentNode.replaceChild(span, el); } });
 <i>Stu#</i> <i>Last Name</i> <i>First Name</i>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM