Remove style on specific tags in WordPress (Javascript)

In WordPress, <img> is inside <a> tag like below.

<a>link text</a>
<a><img src="#"></a>

I added style of dotted border to the bottom of <a>, but there’s also dotted border under every picture I post.

Read More

So I tried to add a function in function.php, in order to remove border of <a><img src="#"></a>, but it failed. Please help me with code below.

function removeAnchorBorder() {
  var anchorWithPic = document.getElementsByTagName("a");
  if (anchorWithPic.contains(img) = true) {
    anchorWithPic.style.border = "none";
}
add_filter("the_content", "removeAnchorBorder");

Related posts

1 comment

  1. Since CSS doesn’t have look-ahead, you can’t override it with plain CSS and must resort to using JavaScript.

    This is a very naive approach, with much logic that could be optimized or abstracted to use jQuery if you prefer:

    var withoutImg = Array.prototype.slice.call(document.querySelectorAll('a'),0); 
    var withImg = Array.prototype.slice.call(document.querySelectorAll('a img'),0);
    
    withoutImg.forEach(function(node){ 
      node.style.borderStyle = "dotted";
    });
    
    withImg.forEach(function(node){ 
      node.parentElement.style.borderStyle = "none";
    });
    

    Here is a visual example.

    Also note that .forEach() may not be available in all browsers, and the Array slice reference is just a trick to convert the selected NodeList into actual iterable arrays.

Comments are closed.