Skip to content Skip to sidebar Skip to footer

Split A Image Tag On Html String

code:

'hi split html string'

'now'

Solution 1:

I'm not completely sure I understand your end goal, but if you want to remove the image from the HTML, you can use the DOM. First create a dummy element and set its innerHTML to the HTML string:

var dummy = document.createElement('div')
dummy.innerHTML = html

Now you got a div that contains your HTML structure as DOM elements. But, what you want is your div, not the dummy one:

var div = dummy.children[0]

Then loop the children, check if it's an image and remove it if so:

for (var i=0; i<div.children.length; i++) {
  var child = div.children[i]
  if (child.tagName == 'IMG') {
    div.removeChild(child)
  }
}

You can append the div to the DOM:

document.body.appendChild(div)

Or you can get back the HTML as a string and without the images:

div.innerHTML
//^ <p>"hi split html string"</p><br>"now""second tag is coming"<br><h1>end here</h1>

Also note that your HTML is not valid, you didn't close the paragraph with </p>, and so the above won't work if it isn't valid.

Post a Comment for "Split A Image Tag On Html String"