skip to Main Content

I have this :

<div class="blog-page-nav-previous">
    <a href="my-link" class="blog-link">&lt;&lt;Previous</a>
</div>

I’m trying to find all instances of the class blog-page-nav-previous and replace the text inside the <a> tag: &lt;&lt;Previous with an image of my own.

How do I do that?

4

Answers


  1. This should work:

    var myClasses = document.getElementsByClassName("blog-page-nav-previous");
    
    for (var i = 0; i < myClasses.length; i++) {
      myClasses[i].innerHTML = "<img src='image.jpg'>";
      }
    <div class="blog-page-nav-previous">
     <a href="my-link" class="blog-link">Previous</a>
    </div>

    If you want the image to have keep the same link as what "Previous" is set as, change the getElementByClassName to look for "my-link" instead of "blog-page-nav-previous"

    Login or Signup to reply.
  2. You could try this

    var a = document.getElementsByClassName("blog-page-nav-previous");
    
    a.forEach(function(a){
      a.outerHTML = '<img src="images/image.jpg" alt="image">'
    });
    

    If you are trying to only replace the contents of the element you could replace a.outerHTML with a.innerHTML

    Login or Signup to reply.
  3. Since you’re asking for a jQuery solution:

    // Select all the <a> tags inside .blog-page-nav-previous and change their innerHTML to an <img> tag:
    $('.blog-page-nav-previous a').html('<img src="foo.jpg">');
    <div class="blog-page-nav-previous">
        <a href="my-link" class="blog-link">&lt;&lt;Previous</a>
    </div>
    Login or Signup to reply.
  4. I think you want the image to work as a link, if yes then I have a solution for you

    <div class="blog-page-nav-previous">
        <a href="my-link" class="blog-link"><img src="example.png"></a>
    </div>
    

    This should work and sorry if this is not the answer you want

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search