skip to Main Content

I’m trying to change only the word Phone: in the second last line to Tel. in the following code block. The 123-456-7890 would stay after the change. I’ve tried this different ways and nothing works. Can someone provide me with a JavaScript or jQuery script to do that? Here is the code block.

 <div class="staffdirectory imagebase section">
    <div class="staff_member">
    <div class="staff_photo nophoto"></div>
    <div class="staff_name nophoto-name">
    <p><span class="staff_name_bolded">Lname, Fname</span></p>
    <p><span>IT Department</span></p></div>
    <div class="staff_contact nophoto-contact">
    <p>123 Building Center</p>
    <p>Phone: 123-456-7890</p>
    </div><div class="clear_all"></div></div>

After the script runs, the resulting HTML would be:

   <div class="staffdirectory imagebase section">
   <div class="staff_member">
   <div class="staff_photo nophoto"></div>
   <div class="staff_name nophoto-name">
   <p><span class="staff_name_bolded">Lname, Fname</span></p>
   <p><span>IT Department</span></p></div>
   <div class="staff_contact nophoto-contact">
   <p>123 Building Center</p>
   <p>Tel. 123-456-7890</p>
   </div><div class="clear_all"></div></div>

Thank you for your advice!

I’ve tried:

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
   $(document).ready(function(){
   $('#demo').text('The replaced text.');
   });
   </script>
   <div id="demo">
      <p>The initial text</p>
   </div>

But I don’t want to replace all of the <p>, just a piece of it.

2

Answers


  1. Use the :contains() selector to find the <p> that has Phone: and perform the replacement.

    $(".staff_contact p:contains(Phone:)").text(function(i, text) {
        return text.replace('Phone:', 'Tel:');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="staffdirectory imagebase section">
      <div class="staff_member">
        <div class="staff_photo nophoto"></div>
        <div class="staff_name nophoto-name">
          <p><span class="staff_name_bolded">Lname, Fname</span></p>
          <p><span>IT Department</span></p>
        </div>
        <div class="staff_contact nophoto-contact">
          <p>123 Building Center</p>
          <p>Phone: 123-456-7890</p>
        </div>
        <div class="clear_all"></div>
      </div>
    Login or Signup to reply.
  2. I added a class="PhoneNumber" to all <p> that contain a phone number and then run a simple replace script on them as follows

    collection = document.getElementsByClassName("PhoneNumber")
    
    Array.from(collection).forEach(element => {
        string = element.innerText.replaceAll("Phone:", "Tel:")
        element.innerText = string
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search