Bob
Bob

Reputation: 848

Jquery prepend based on own content

I need something in jQuery but can't figure it out.

I got this html:

 <h2>My Name 1</h2>
 <h2>My Name 2</h2>
 // many more

In jQuery I want to get the content of this `h2' and need that for:

 <h2><a href="My Name 1">My Name 1</a></h2>

This is working:

 jQuery(".content h2").prepend("<a href=''>").append("</a>");

But the href has to be based on its content... How to do that?

Thanks!

Upvotes: 2

Views: 66

Answers (5)

Adesh Gorade
Adesh Gorade

Reputation: 11

$(function () {
$(".content h2").each(function (n) {
var x =$('h2').eq(n).text();
var y = x.replace(/\s/g, '');
$(".content h2").eq(n).empty().append("<a href="+y+">"+x+"</a>");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content">
 <h2>My Names 1</h2>
 <h2>My Names 2</h2>
 <h2>My Names 3</h2>
 <h2>My Names 4</h2>
 <h2>My Names 5</h2>
</div>

Blockquote

Upvotes: 1

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this..

$(document).ready(function(){
    var href = 'test.html'; 
jQuery(".content h2").prepend("<a href='"+href+"'>").append("</a>");
});

Upvotes: 0

dfsq
dfsq

Reputation: 193291

You can't append a chunk of HTML element like the half of a tag. Browser fixes such an invalid HTML and won't render it.

Use wrapInner method:

$('.content h2').wrapInner('<a href="something"></a>');

If link href attribute somehow depends on actual h2 content then you should use function as wrapInner arguments, see Rory McCrossan's answer. For example to set href to be the same as h2 content it can be:

$('h2').wrapInner(function() {
    return '<a href="' + $(this).text() + '"></a>';
});

Upvotes: 2

lshettyl
lshettyl

Reputation: 8181

So, grab the content of H2 and then append A with href and text as the grabbed content.

var h2Text = $(".content h2").text();
$(".content h2").empty().append( $("<a/>", { href: h2Text, text: h2Text }));

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337626

I'm not sure that what you have is working as you expect because you can only append whole elements. Your current code would end up with something like this:

<h2>
    <a href=''></a>
    My name 1
    <a></a>
</h2>

Given that you want to effectively wrap the text of the h2 in an a element you can use wrapInner() with a handler function containing the logic to set the href. Try this:

jQuery(".content h2").wrapInner(function() {
    var href = 'foo.php'; // your logic here
    return '<a href="' + href + '"></a>';
});

Example fiddle

Upvotes: 2

Related Questions