How to get the text of a div which is not a part of any other container in JQuery?

后端 未结 6 1641
野趣味
野趣味 2021-02-05 15:10

This should be real easy. Given below is the HTML.

#Attachment#
6条回答
  •  野的像风
    2021-02-05 15:46

    Since your text happens to be the first child node of the

    :

    var firstChild = $("#attachmentContainer")[0].firstChild;
    var textValue  = firstChild.nodeType == 3 ? $.trim(firstChild.nodeValue) : "";
    

    The nodeType check is meant to be a safeguard - it makes sure you are actually handling a text node - the firstChild might be something different after all. React accordingly, this is just an example.

    To retrieve the value of all text children (or a specific one), just loop over the childNodes collection of your element, concatenating all bits you find into a string:

    // the optional "at" parameter lets you define which text node you want
    // if not given, this returns all text nodes concatenated
    $.fn.ownText = function(at) { 
      var result = [], node = this[0];
      if (!(node && node.childNodes)) return;
      for (var i=0; i

提交回复
热议问题