This is" />

This is" />

This is"/>

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

71 Views Asked by At

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.

2

There are 2 best solutions below

1
Aryan Anshuman On BEST ANSWER
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);
8
Jerico On

Here's a solution I came up with to hide a number of elements with a for loop. I made this code to be reusable and easy to put into the current code.

//Is an array of all elements in div
let container = document.querySelector(".container").children;
let shownElement = 2;

for(let i = 0; i < container.length; i++){
  container[i].setAttribute("id", i + 1);
  console.log(container[i].outerHTML);
  
  if(i == shownElement - 1){
    let reI = i + 1;
    console.log("shown element: " + reI)
  } else {
    container[i].style.display = "none";
  }
}
<div class="container">
  <p>This is a paragraph.</p>
  <p>Lorem ipsum.</p>
  <p>Stuff is here.</p>
</div>

Edit: I made it so we don't know the order of elements on a random webpage by taking away the P's ID. Then we make our own order and hide all elements except the one we want shown. I hope this helps you based on what I understand so far. If it somewhat does be more clear on the asking. (I create the ID order on my own because all elements on a webpage are coded in line to work anyway. That's why I'm confused. I'm even more confused after the statement of can we do it with no ID? )

Hope this helps :) Upvote if it does.