Home » Jquery » jquery – How to remove span tag which has no attribute in a HTML block using Javascript or ExtJs-Exceptionshub

jquery – How to remove span tag which has no attribute in a HTML block using Javascript or ExtJs-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

using Javascript, I am trying to remove span tags within HTML content which has no attribute, but have not found a solution yet.

for example, if a html content is

<p>
<span>
<span class="asset">&nbsp;</span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;">&nbsp;</iframe>
</span>
</p>

expected result is,

<p>
<span class="asset">&nbsp;</span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;">&nbsp;</iframe>
</p>
How to&Answer:

Try this:
This has only one problem: The span must be the last child of its parent, but for your example it might work:

The changes cannot be seen without displaying the innerHTML of the p (as I’ve done below on the 2nd snippet) or inspecting the result.

let spans = document.querySelectorAll("span");
for (let i = 0; i < spans.length; i++) {
  let span = spans[i], ih, p;
  if (span.hasAttributes() === false) {
    ih = span.innerHTML;
    p = span.parentNode;
    p.removeChild(span)
    p.innerHTML += ih;
  }
}
<p>
<span>
<span class="asset">&nbsp;</span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;">&nbsp;</iframe>
</span>
</p>

Here is an example of console.loging it:

let spans = document.querySelectorAll("span"), arr = [];
for (let i = 0; i < spans.length; i++) {
  let span = spans[i], ih, p;
  if (span.hasAttributes() === false) {
    ih = span.innerHTML;
    p = span.parentNode;
    p.removeChild(span)
    p.innerHTML += ih;
    arr.push(p); //added to console.log the innerHTML of the parent
  }
}

//console.log the parents' innerHTML
for (let j = 0; j < arr.length; j++) {
  ih = arr[j].innerHTML;
  console.log(ih);
}
<p>
<span>
<span class="asset">&nbsp;</span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;">&nbsp;</iframe>
</span>
</p>