Mostafa Said
Mostafa Said

Reputation: 1015

How can I use an HTML tag to wrap all elements that follow a specified element?

I'm working with Vue 2 and Sanity.io and I need a way to surround all elements that comes after a specific element with HTML tag, and then surround this element along with the followed elements with another HTML tag.

let's say every <h1> will have multiple paragraphs that follows it and then another <h1> and another paragraphs follow it. I want those to be divided with summary and details HTML tags.

For example, I have data coming over from Sanity and it goes like this.

<h1>text</h1>
<p>text</p>
<p>text</p>
<p>text</p>

<h1>text</h1>
<p>text</p>
<p>text</p>
<p>text</p>

I need a way to manipulate the DOM to make it read my data like this

<details>
<summary><h1>text</h1></summary>
<p>text</p>
<p>text</p>
<p>text</p>
</details>

<details>
<summary><h1>text</h1></summary>
<p>text</p>
<p>text</p>
<p>text</p>
</details>

To clarify more, I'm using protable-text-to-vue package which sends back the data as vue components blocks. basically they are coming from sanity in a similar form to the example mentioned above.

Upvotes: 0

Views: 109

Answers (1)

Mostafa Said
Mostafa Said

Reputation: 1015

I was able to accomplish this by using the mounted() to call getElementsByTagName() :

https://www.w3schools.com/jsref/met_element_getelementsbytagname.asp

Then I looped over each element and wrapped it with <summary> and <details> tags.

ele.outerHTML =
                '<details><summary>' +
                ele.outerHTML +
                '</summary></details>'

And then I moved all h1 children inside the <details> tags by using appendChild().

let children = document.querySelectorAll(
              `details:nth-child(index) ~ *:not(h1,h1 ~ *)`
)

Array.from(children).map(function(child) {
        document
        .getElementById(`uniqueId`)
        .appendChild(child)
})

Upvotes: 1

Related Questions