三行代码  ›  专栏  ›  技术社区  ›  Tarunpreet Singh

如何获取元素的html但忽略子标记(br标记除外)

  •  0
  • Tarunpreet Singh  · 技术社区  · 2 月前
    <div class="test"> Div Text lorem ipsum <br> lorem ipsum <p class="some_class">Paragraph Content <br> tag and again child nested in it <span> span content</span></p></div>.
    

    我想得到div元素的html。这里有一个棘手的部分,如果我使用.html(),它还将包括 <p class="some_class">....<span>...</span>...</p>

    同侧文字 <br> lorem ipsum段落内容 <br>

    0 回复  |  直到 2 月前
        1
  •  2
  •   Shashank Gb    2 月前

    如果只希望在任何元素中显示文本,可以使用 innerText <br> 标记结果。所以你可以用 内部文本 首先,然后更换线路馈线( \n )与 <br>

    var divtext = document.getElementsByClassName('test')[0].innerText;
    console.log(divtext);
    console.log(divtext.replaceAll('\n', '<br>'));
    <div class="test"> Div Text lorem ipsum <br> lorem ipsum <p class="some_class">Paragraph Content <br> tag and again child nested in it <span> span content</span></p></div>
        2
  •  1
  •   Parking Master Mr Proud    2 月前

    您可以使用JavaScript(while/for)循环。

    这里有一个活生生的例子。

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Get Children Content with br tag</title>
      </head>
      <body>
       <div id="test"> Div Text lorem ipsum <br> lorem ipsum <p class="some_class">Paragraph Content <br> tag and again child nested in it <span> span content</span></p></div>.
      </body>
      <script>
        //   get all the content of the  div tag
        let test = document.getElementById("test");
        let testData = test.innerHTML;
    
        let finalText = "";
    
        // this variable will decide to capture the lettes when captured in loop.
        let capture = true;
    
        // starting to over all the cahracter in the text content
        for (let i = 0; i < testData.length; i++) {
          let recursive = false;
          if (
            testData.charAt(i) == "<" &&
            testData.charAt(i + 1) == "b" &&
            testData.charAt(i + 2) == "r"
          ) {
            //   if <br> tag is receved skip 4 char and increment the i value
            capture = true;
            recursive = true;
          } else if (testData.charAt(i) == "<") {
            //   if < is found stop capturing
            capture = false;
          } else if (testData.charAt(i) == ">") {
            //   if > is found start  capturing but skip this iteration
            capture = true;
          }
    
          //   main capturing code
          if (capture) {
            if (testData.charAt(i) != ">") {
              finalText = finalText + testData.charAt(i);
            }
            if (recursive) {
              finalText =
                finalText +
                testData.charAt(i + 1) +
                testData.charAt(i + 2) +
                testData.charAt(i + 3);
              i = i + 3;
            }
          }
        }
        console.log(finalText);
      </script>
    </html>