Home > Enterprise >  How to get parent element html but not children tags?
How to get parent element html but not children tags?

Time:11-13

I am not sure I gave correct title to my question but I want to ask to do something like:

I want to get HTML content of parent element. By doing this, this will also include HTML tags of children element but I don't want that. I just want children HTML.

For Example:

<div class="test"> This is content of div
  <p class="boring_class" style="borinhdlfj"> This is paragraph<br> content.As you can see I have added <br> tag</p>
</div>

from above example If I use .text() jquery method to get div content I will get text only but not <br> tag. But if I use .html() jquery, this will also include <p style='dflkdjf'>....</p> but I don't want that.

I just want html of children element which is:This is paragraph<br> content.As you can see I have added <br> tag.

How can I achieve that?

Final output should look like:

This is content of div This is paragraph <br> content.As you can see I have added <br> tag

CodePudding user response:

As one possible interpretation of the question:

Get html of all children, including text [not in a children nodes]

You can use .contents() to include the text nodes of the parent (the parts that aren't in tags, eg "This is content of div") then loop through those to get either text or html depending on where it is, giving:

var output = $(".test").contents().map((i, e) => {
    if (e.nodeType == 3)
      return $(e).text();
    return $(e).html()
  })
  .toArray()
  .join(" ");

console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"> This is content of div
  <p class="boring_class" style="borinhdlfj"> This is paragraph<br> content.As you can see I have added <br> tag</p>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note this includes all whitespace (newlines) which were not included in the question's example output, so you may need to remove these for an exact match.

CodePudding user response:

You can accomplish this in regular javascript by using innerHTML as shown below.

For more info, see: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

const list = document.getElementsByClassName("test")[0];

const inner = list.innerHTML;

const noP = inner.replace(/<p[^>]*>/g, "").replace(/<\/p[^>]*>/g, "").replace(/\n/g,'');

console.log(noP);
<div class="test"> This is content of div 
<p class="boring_class" style="borinhdlfj"> This is paragraph<br> content.As you can see I have added <br> tag</p>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related