dom range.setStart / setEnd

后端 未结 2 2071
深忆病人
深忆病人 2021-02-20 17:52

I am trying to bold only the text hel in this fiddle http://jsfiddle.net/yarkpakv/ but it does not seem to be working, what am I doing wrong???

2条回答
  •  时光取名叫无心
    2021-02-20 18:15

    Got it ...

    var range = document.createRange();
    var root_node = document.getElementById("test");
    
    range.setStart(root_node.firstChild,0);
    range.setEnd(root_node.firstChild,3);
    
    var newNode = document.createElement("b");
    
    range.surroundContents(newNode);
    

    In all of the documentation, they are referencing the "Child" ... this solves that. In the case of your Fiddle, it will wrap the Letter "h" and the two

    and

    tags. Take them out and hel becomes bold.

    UPDATE:

    Apparently, whitespace will cause problems ...

    HTML ...

    TEST

    Working here ... jsFiddle

    Reference ... HERE

提交回复
热议问题