0

I need parse my document. I mean I want to replace "div" to for example "p"

so the code:

<section class="X">
<p>Some title</p>
<div data-newname="p"></div>
</section>

becomes to:

<section class="X">
<p>Some title</p>
<p></p> <- here is replacement 
</section>

So the point is, I need to find element by data-attribute and replace start (<div>) and end (</div>) to anything i want to.

but I dont have idea how can I do this. I have many divs element with data attribute and I need to replace to {{Start::test}}{{End::test}} - the test is from data-attribute, or whatever..

I will be grateful for any help from you guys..

1
  • Is there nothing that will uniquely identify the element to be changed? Commented Jun 25, 2019 at 20:03

1 Answer 1

0

Using jQuery you could use https://api.jquery.com/replaceWith/ and return a brand new jQuery Element Object

$('[data-newname]').replaceWith(function() {
  const tagName = $(this).data('newname')
  return $(`<${tagName}/>`, {text: 'demo'});
});
p {padding: 10px; outline: 1px solid red;}
<section class="X">
  <p>Some title</p>
  <div data-newname="p"></div>
</section>


<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

and inside the {} you can pass any available Method you like (see example above using jQuery's text Method)

Keep the content

if you want to keep the content you can similarly do:

$('[data-newname]').replaceWith(function() {
  const tagName = $(this).data('newname')
  return $(`<${tagName}/>`, {html: $(this).html()});
});
p {padding: 10px; outline: 1px solid red;}
<section class="X">
  <p>Some title</p>
  <div data-newname="p">Lorem <b>ipsum</b> <i>dolor</i></div>
  <div data-newname="marquee">This still works wohaa</div>
</section>


<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

P.S:
don't get confused by this

$(`<${tagName}/>\`, 

it's just the same as $('<'+ tagName +'/>', just using Template Literal and inserting a variable into the string using the placeholder ${}

https://api.jquery.com/replaceWith/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.