1

I wonder how to change the HTML tag without replacing the contents. I did something like this:

$('#test > span').replaceWith('<div>' + $('#test > span').html() +'</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <span>hello</span>
  <span>hello2</span>
  <span>hello3</span>
</div>

Works, but still displays the first value (look code snippet). I think I need to merge .replaceWith() with $(this) but I can't quite do it.

2 Answers 2

3

To do what you require you can pass a function to replaceWith(). This function accepts two arguments, the index of the current element and its content, and returns the new element to make the replacement. As such you can use the second argument to change the parent tag while keeping the same content, like this:

$('#test > span').replaceWith((i, content) => `<div>${content}</div>`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <span>hello</span>
  <span>hello2</span>
  <span>hello3</span>
</div>

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

Comments

0

You could also use a RegExp to replace all <span></span> with <div></div> in the innerHTML:

// jQuery version

$('#btnReplaceHTML').click(() => {
  const re = /(<\/?)span(>)/gm
  $('#test').html($('#test').html().replace(re, '$1div$2'));
})



/*
// "Vanilla" JavaScript version

document.getElementById('btnReplaceHTML').addEventListener('click', () => {
  const re = /(<\/?)span(>)/gm
  const elem = document.getElementById('test');
  elem.innerHTML = elem.innerHTML.replace(re, '$1div$2');
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <span>hello</span>
  <span>hello2</span>
  <span>hello3</span>
</div>
<button id="btnReplaceHTML">replace HTML</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.