Home > Software design >  Target text within <a> and wrap it in a span
Target text within <a> and wrap it in a span

Time:02-28

How can I target the text within an <a> and wrap it in a span?

So original code is:

<a href="#"><span ><img src="toggle.svg" title="Read more" alt="Read more"></span>
Job title #01
<span >Hello</span>
</a>

What I want it to become is:

<a href="#"><span ><img src="toggle.svg" title="Read more" alt="Read more"></span>
<span >Job title #01</span>
<span >Hello</span>
</a>

Who can I target the text and add span tags around it? Cant seem to target the text of the

CodePudding user response:

You can use .contents() which returns all the child nodes of the element, including text nodes.

$('a').contents()

Then we iterate, check the text node, grab the text and replace it with the HTML.

if (this.nodeType == 3) {
    var u = this.nodeValue;
    $(this).replaceWith('<span >'   u   '</span>');
}`

Note:

  1. It works if only you keep the structure of the HTML as-is. changing HTML will break this code

Working Example below

$('a').contents().each(function() {
  if (this.nodeType == 3) {
    var u = this.nodeValue;
    $(this).replaceWith('<span >'   u   '</span>');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#"><span ><img src="toggle.svg" title="Read more" alt="Read more"></span>
Job title #01
<span >Hello</span>
</a> What I want it to become is:

CodePudding user response:

//console.log(document.querySelector('a').childNodes[1]);

document.querySelector('a').childNodes[1].innerHTML = `<span>${document.querySelector('a').childNodes[1].wholeText}</span>`;

console.log(document.querySelector('a').childNodes[1]);

//to use in jquery 
//$('a').childNodes[1].innerHTML = `<span>${$('a').childNodes[1].wholeText}</span>`;
<a href="#"><span ><img src="toggle.svg" title="Read more" alt="Read more"></span>
Job title #01
<span >Hello</span>
</a>

  • Related