Search code examples
javascripthtmldomdom-manipulation

How to trim the innerHTML string upto a specific element inside it?


I want to find out how we can get the innerHTML string upto a specific element inside the element.

Example :

<div id="common-name">
        <p id="P1">This is a paragraph 1.</p>
        <p id="P2" >This is a paragraph 2 .</p>
        <p id="P3">This is a paragraph 3.</p>
</div>

Say we want it upto the element with id: P2 , so output as a string would be like :

<div id="common-name"><p id="P1">This is a paragraph 1.</p>

(Also if any implementation exists can it be done if the elements didn't have the ID, rather the ref as a object in JavaScript.

[EDIT] The thing i m trying to solve here is, say if i have the element with #p3 as an object and the div container , now i want to get the innerHTML upto the #p2 element. @Jerico's answer will work if things are arranged neatly like p1 -> p2 -> p3, but if the order are interchanged it might not work. Something to work around that?

I tried getting the innerHTML content as a string but have no idea how to get the rest of the text after the element, so that i could subtract it from the original string to have the same output.


Solution

  • var container = document.getElementById('common-name'); var targetElement = document.querySelector('#common-name #P2'); var innerHTMLString = '' ; for (var i = 0; i < container.children.length; i++) { innerHTMLString += container.children[i].outerHTML; if (container.children[i] === targetElement) break; } console.log(innerHTMLString);