Reputation: 6477
I have a bunch of these on a page:
<div class="item" id="555">
<div class="wrapper>
<p>Make Link One</p>
</div>
<p class="action">Make Link Two</p>
</div>
How can I dynamically make the 2 texts links based on the id 555? ie. They both should be links to http://555
There is a unique business requirement which is the reason they're not just normal hrefs to begin with.
Upvotes: 0
Views: 513
Reputation: 51685
I would do it like this, assuming that you’d like it to apply to every p
which is a child of an element with the item
class:
$(function(){
$('.item p').each(function(){
var $this = $(this);
$this.contents().wrap($('<a>', { href: $this.closest('.item').attr('id') }));
});
});
Upvotes: 0
Reputation: 1955
$(document).ready(function(){
$(".item p").each(function(){
var t1 = $(this).text();
var linkid = $(this).parents('.item:first').attr("id");
$(this).parent().append('<a href="http://' + linkid + '">' + t1 + '</a>');
$(this).remove();
});
});
Upvotes: 1
Reputation: 75993
You can just bind a click event handler to the containing div that uses it's own ID to redirect the user:
$('.item').on('click', function () {
window.location = 'http://' + this.id;
});
If you have other content inside the container element that should not trigger the redirect then you can bind to the <p>
elements inside the container:
$('.item').on('click', 'p', function () {
window.location = 'http://' + $(this).parents('.item:first')[0].id;
});
BTW, IDs should not start with numbers. Here's a link to the correct syntax for IDs: What are valid values for the id attribute in HTML?
Note that .on()
is new in jQuery 1.7. In the first example replaces the depreciated .bind()
and in the second example it replaces the depreciated .delegate()
.
Upvotes: 1
Reputation: 17553
$('p').each(function(){
var $this = $(this);
var href = $this.parents('.item:first')[0].id;
$this.wrap('<a href=http://"' + href + '">');
});
.each
loops through the found p
elements. It then looks for the parent iwth a class .item
($this.parents('.item:first')
) to get the id. The [0]
part turns the jQuery object into just a standard DOM element so that we can easily grab the id
property from that element (you could also have done $this.parents('.item:first').attr('id')
to stick with pure jQuery). Finally, we wrap the p
in an anchor tag with the correct href
.
Upvotes: 1