dennisbest
dennisbest

Reputation: 419

Setting an attribute from element contents

Lets say you have this:

<ul>
  <li>[foo] more stuff here</li>
  <li>[bar] stuff here</li>
  <li>[123] stuff here</li>
</ul>

and you want this:

<ul>
  <li id="foo">more stuff here</li>
  <li id="bar">stuff here</li>
  <li id="123">stuff here</li>
</ul>

Using jQuery, what's the simplest way to get this?

Upvotes: 1

Views: 44

Answers (3)

Kamehameha
Kamehameha

Reputation: 5473

We can do this using regex.- FIDDLE

$(document).ready(function(){
    $('ul').children().each(function(){
        $strVal=$(this).text();
        //extracting the required id value.
        var $idVal=((/\[.*\]/g.exec($strVal)).toString()).replace(/(?:\[|\])/g,"");
        $(this).html($strVal.replace(/\[.*\]/g,""));
        alert($idVal);
        $(this).attr('id',$idVal);
    });
});

Upvotes: 0

hunter
hunter

Reputation: 63512

$("ul li").each(function(){
    $li = $(this);
    var text = $li.text();
    var id = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
    $li.attr("id", id).text(text.replace("[" + id + "]", ""));
});

fiddle: http://jsfiddle.net/hunter/FDTcj/


fiddle with other brackets: http://jsfiddle.net/hunter/FDTcj/1/

Upvotes: 4

Adrian
Adrian

Reputation: 46433

jquery alone won't do this, you'll need to parse the contents. Personally I would use regular expressions:

$("li").each() {
    var regex = /\[([^\]]+)\] (.*)/;
    var matches = regex.exec($(this).html());
    $(this).attr("id", matches[1]);
    $(this).html(matches[2]);
};

Upvotes: 0

Related Questions