Add text before or after an HTML element

前端 未结 6 1992
误落风尘
误落风尘 2020-12-09 02:34

If i have an HTML element like

with some text inside or another elements can I add before or after this div some text data without an html element,
相关标签:
6条回答
  • 2020-12-09 02:38

    Something like this should do it:

    <script type="text/javascript">
      var parent = document.getElementById('parentDiv');
      var sibling = document.getElementById('childDiv');
      var text = document.createTextNode('new text');
      parent.insertBefore(text, sibling);
    </script>
    
    0 讨论(0)
  • 2020-12-09 02:40

    Just for the record:

    div.insertAdjacentHTML( 'beforeBegin', yourText );
    

    where div is your child-DIV.

    Live demo: http://jsfiddle.net/ZkzDk/

    0 讨论(0)
  • 2020-12-09 02:44

    You can add text node. Create node - document.createTextNode('text') and then insert/append/replace - do whatever you want.

    0 讨论(0)
  • 2020-12-09 02:46

    In regards to the topic and the users question for inserting before or after, here is an example for after:

       var text = document.createTextNode("my text must be added here.");
       var childTag = document.getElementById("childDiv");
    
       childTag.parentNode.insertBefore(text, childTag.nextSibling);
    

    If the childTag does not have any siblings, it is okay because the insertBefore method handles this case and simply adds it as the last child.

    Also can possibly use the appendChild() method after creating text node then add your childTag via the parentNode.

    0 讨论(0)
  • 2020-12-09 02:49

    If you just need text, I find that element.insertAdjacentText(position, text) is flexible for many scenarios and is also compatible with older browsers like IE6. Where position is exactly where you want the text to be and text is the text node or just a string. The options are:

    • 'beforebegin' Before the element itself.
    • 'afterbegin' Just inside the element, before its first child.
    • 'beforeend' Just inside the element, after its last child.
    • 'afterend' After the element itself.

    Like this:

    let div = document.getElementById('parentDiv');
    div.insertAdjacentText('afterbegin', 'My Plain Text..');
    
    0 讨论(0)
  • 2020-12-09 02:59

    Yes, you can create a text node with document.createTextNode('the text')

    Then you can insert it like an element, with appendChild or insertBefore.

    Example that insert a text before #childDiv:

    var text = document.createTextNode('the text');
    var child = document.getElementById('childDiv');
    child.parentNode.insertBefore(text, child);
    
    0 讨论(0)
提交回复
热议问题