Contents of an H3 as the H3's ID

I need to get the contents of an <h3></h3> and then lowercase the contents and remove the spaces (replacing them with - or _) and then inject them into the ID of the <h3> .

So, for example...

<li class="widget-first-list"><h3>About This Stuff</h3></li>
<li class="widget-first-list"><h3 id="about-this-stuff">About This Stuff</h3>

This should exist for a load of h3s on the page, so it needs to include '$this' somewhere.

Hope this makes sense - I am okay with jQuery but this has been causing me a few problems.


Since you specified jQuery, here you go:

$("h3").each(function() {
    var me = $(this);
    me.attr("id",me.text().toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-'));
});

This replaces all non-alphanumeric characters with - , and then strips out multiple consecutive - characters.

In plain JS (much more efficient):

(function() {
    var tags = document.getElementsByTagName("h3"), l = tags.length, i;
    for( i=0; i<l; i++) {
        tags[i].id = tags[i].firstChild.nodeValue.toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-');
    }
})();

Even better, checking for duplicates:

(function() {
    var tags = document.getElementsByTagName("h3"), l = tags.length, i, newid, n;
    for( i=0; i<l; i++) {
        newid = tags[i].firstChild.nodeValue.toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-');
        if( document.getElementById(newid)) {
            n = 1;
            do {n++;}
            while(document.getElementById(newid+'-'+n));
            newid += '-'+n;
        }
        tags[i].id = newid;
    }
})();

一个办法:

$("h3").each(function() {

    var content = $(this).html().replace(/ /g,'_').toLowerCase();
    $(this).attr("id",content);

});
链接地址: http://www.djcxy.com/p/21260.html

上一篇: 如何使用nodejs使搜索大小写不敏感?

下一篇: 一个H3的内容作为H3的ID