简体   繁体   中英

Change style of textnode but not child nodes

I am trying to make a collapsible hierarchy. In which I am trying to highlight the place that user is expanding. I tried to set the font-weight property to BOLD to highlight. But this is highlight all the childern also.

<ul>
    <li id="A">A
         <ul>
            <li id="A_1">1</li>
            <li id="A_2">2
                <ul>
                    <li id="A_2_2.1">2.1</li>
                    <li id="A_2_2.2">2.2</li>
                </ul>
            </li>
         </ul>
     </li>
  </ul>

What is am trying to do here is if user selects A>2>2.2 . I will highlight the textnode of the 3 li nodes.

$('li').on('click', function (event) {
     event.preventDefault();
     $('ul:first',event.target).toggle("slow");
     document.getElementById($(event.target).attr("id")).setAttribute("style","font-weight:bold");
     event.stopPropagation();
});

The problem here is when I am running above code it is highlighting all the list not just the textnode.

Final should look like

**A**
  1
  **2**
    2.1
    **2.2**

The child elements will be defaulting to font-weight: inherit .

If you don't want them to inherit the value from their parent element, then you will have to explicitly set the value to something else.

Alternatively, wrap the text node you want to style in another element (eg a span) and then make that bold.

Here are some tips.

  1. By default, make sure all li elements have normal font-weight
  2. Set a class for the selected li element, lets call it .selected
  3. If you're animating the list into view on click, hide the ul under any list item

CSS:

ul li {
    font-weight: normal;
}
li.selected {
    font-weight: bold;
}
li > ul {
    display: none;
}

As you can see from above, we're using CSS specificity to our advantage.

Then, you'll need to clean up the JavaScript. Here's what that would look like.

JavaScript:

$('li').on('click', function (event) {
    event.preventDefault();
    event.stopPropagation();

    var $li = $(this);

    $li.toggleClass("selected"); // toggle the selected class on the clicked element

    $li.children().toggle("slow"); // Get the ul and toggle its display
});

Hopefully, this should get you on the right track.

Demo: JsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM