Reputation: 317
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>');
});
Upvotes: 3
Views: 677
Reputation: 28196
You can, of course, also do this without jQuery:
document.querySelectorAll('.menu a').forEach(a=>{
a.style.display="none";
a.insertAdjacentHTML("afterend",`<p class="pdf">${a.textContent}</p>`)
});
p.pdf { color: red }
<div class="menu">
<a href="page.html">Page 1</a>
<a href="page2.html">Page 2</a>
</div>
<p><a href="somewhere.html">no action was taken here, since this is not part of the menu div.</a> And that is a fact.</p>
Upvotes: 0
Reputation: 171669
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>
Upvotes: 2
Reputation: 3241
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/
Upvotes: 0