Robert E
Robert E

Reputation: 740

Use jquery to write an ID based on text in a span tag

I am not sure if this is even possible, with that said... below is a sample of HTML I am working with. I want to, with jQuery, grab the product name and insert it as an ID on the paired span tag with the class "support", replacing spaces with underscores.

<div><span class="title">Product1 Name</span> <span class="support"></span></div>
<div><span class="title">Product1 Name</span> <span class="support"></span></div>
<div><span class="title">Product1 Name</span> <span class="support"></span></div>
<div><span class="title">Product1 Name</span> <span class="support"></span></div>

Below would be the desired HTML that jQuery would modify. Is this possible?

<div><span class="title">Product1 Name</span> <span class="support" id="product1_name"></span> </div>
<div><span class="title">Product2 Name</span> <span class="support" id="product2_name"></span> </div>
<div><span class="title">Product3 Name</span> <span class="support" id="product3_name"></span> </div>
<div><span class="title">Product4 Name</span> <span class="support" id="product4_name"></span></div>

Upvotes: 0

Views: 525

Answers (2)

Matt Ball
Matt Ball

Reputation: 359776

Yup.

$('span.title').each(function ()
{
    var $this = $(this),
        id = $this.text().toLowerCase().replace(/ /g, '_');
    $this.next().attr('id', id);
});

Demo!

This could very well create elements with duplicate IDs, however. Not good.

Upvotes: 4

Variant
Variant

Reputation: 17365

something like:

(".title").each(function() {$(this).next(".support").attr("id",$(this).html().replace(" ","_"));});

didn't check it but it should work, hope I got the parenthesis count right in the end...

Upvotes: 0

Related Questions