Additional jquery class

Asked 2 years ago, Updated 2 years ago, 49 views

This is a question from jquery.
I would like to automatically add class only when <br> is attached to the html below. What should I do?
I want to add three classes.

<ulid="menu">
<li><a href="menu01">Apple<br>Apple Pie</a><li>
<li><a href="menu02"> grapes</a></li>
<li><a href="menu03">Strawberry<br>Strawberry Short</a></li>
<li><a href="menu04"> pineapple</a></li>
<li><a href="menu05">Tangerine</a></li>
</ul>

I want to change it to the following in jquery

<ulid="menu">
<lic class="aaa">a href="menu01"><span class="bbb">Apple</span>>br>span class="ccc">Apple pie</span>>a>
<li><a href="menu02"> grapes</a></li>
<lic class="aaa">a href="menu03"><span class="bbb">Strawberry</span><br>>span class="ccc">Strawberry Short</span>a>
<li><a href="menu04"> pineapple</a></li>
<li><a href="menu05">Tangerine</a></li>
</ul>

Please let me know.Thank you for your cooperation.

jquery

2022-09-30 14:52

2 Answers

This is a pattern that refers directly to the target HTML as a string and reconstructs the analysis HTML.

$(function()
{
    varreg = newRegExp("^(.*)<[bB][rR]>(.*)$");

    $("#menu>li").each(function(i,e)
    {
        var htmlStr=$(e).children("a").html();

        var result=reg.exec(htmlStr);

        if(result===null)
        {
            return;
        }

        var newHtml='<span class="bbb">'+result[1]+'</span>br>>span class="ccc">'+result[2]+"</span>";

        $(e).children("a").html(newHtml);
        $(e).children("a").addClass("aaa");
    });
});


2022-09-30 14:52

The jQuery selector handles this pattern.

$(function()
{
    $("#menu>li:has(br)").each(function(){
        $(this).addClass("aaa");
        s=$(this).children('a') .html().split("<br>");
        $(this).children('a') .html('<span class=\"bbb\">'+s[0]+'</span>br>>>span class="ccc">'+s[1]+'<span>');
    });
});


2022-09-30 14:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.