简体   繁体   中英

Converting an anchor tag to plain text with jQuery

I am running into a problem with my output of an HTML-to-PDF process where my anchor tags that contain the tel: protocol are kicking back errors when clicked. It turns out that these hrefs are being seen as relative URLs unlike how mailto: is recognized as it's own thing.

I figure that if I can target these elements directly, I could take their content, hide the <a> tag entirely and only display the content in a new element. Maybe this is overthinking it?

Here's where I went: https://jsfiddle.net/BIPC_Sydor/yL8suwno/1/

I wanted to try and target each instance of an <a> tag within a specific div (class of menu). Then copy the content of each instance into a new <p> tag (class of pdf). From there I could hide the old <a> and stylize the new <p> . Unfortunately, it's outputting both anchors' content in more instances that I expected. Is this doable?

My code from the fiddle:

HTML

<div class="menu">
  <a href="page.html">Page 1</a>
  <a href="page2.html">Page 2</a>
</div>

JS

$( '.menu a' ).each(function( i ) {
  var res = $('.menu a').text();
  $('.menu a').after('<p class="pdf">'+ res +'</p>');
});

You can use after(function) and chain hide() to hide the <a> as well

 $('.menu a').after(function() { return $('<p>', {class: 'pdf', text: $(this).text()}) }).hide()
 p.pdf { color: red }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="menu"> <a href="page.html">Page 1</a> <a href="page2.html">Page 2</a> </div>

use value as well in your each() method, and use the value reference to update nodes, else it will update all the nodes.

$( '.menu a' ).each(function( index,value ) {
  var res = $(value).text(); // value is for current iteration
  $(value).after('<p class="pdf">'+ res +'</p>');
  // do something else...
});


Reference here: https://api.jquery.com/jquery.each/

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