WTE
WTE

Reputation: 331

Jquery - Logic should not impact particular ID

Used below HTML/JS for a logic to change h2 to h3.

But, it should not affect the H2 inside "testelement" DIV ID.

Some how this script is not working as expected. please let me know how to fix this?

Thanks

if($('#testelement').length){
  $('body').find('h2').replaceWith(function() {
    return '<h3>' + $(this).text() + '</h3>';
  });
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="testelement">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</div>
<h1>Test Headline 1</h1>
<h2>Headline 2</h2>

Upvotes: 1

Views: 45

Answers (3)

dale landry
dale landry

Reputation: 8610

Pure javascript: create a new element, append the parent of the old, then remove the target element. Along with a conditional to check if you are not inside the targeted ID you wish to exclude.

let target = document.querySelectorAll('h2');

target.forEach((val) => {
  if(!val.parentNode.id.includes('testelement')){ //or... val.parentNode.id !== 'testelement'
    let el = document.createElement('H3');
    el.innerHTML = val.innerHTML;
    val.parentNode.appendChild(el);
    val.parentNode.removeChild(val); 
  }
})
console.log(document.body.children[4])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="testelement">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</div>
<h1>Test Headline 1</h1>
<h2>Headline 2</h2>

Upvotes: 0

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

Just point out the element you don't want to be affected.

.not('#testelement h2')

From w3schools

The :not() selector selects all elements except the specified element.

if($('#testelement').length){
  $('body').find('h2').not('#testelement h2').replaceWith(function() {
    return '<h3>' + $(this).text() + '</h3>';
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="testelement">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</div>
<h1>Test Headline 1</h1>
<h2>Headline 2</h2>

Upvotes: 2

Bekim Bacaj
Bekim Bacaj

Reputation: 5965

Jquery - Logic should not impact particular ID

Yes it does! HTML Elements are immutable.

You can't change the element. You are destroying it for the purpose of replacing it with another, completely different individual and type of the given kind of HTML Elements.

Once the existing Element is destroyed, it's reference ID is unregistered and garbage collected, gone.

ID's are not adn cannot be inherited.

Upvotes: 0

Related Questions