Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to untag spans without id

Would it be possible to find and untag spans that do not have ids within a string? I have a text that has bunch of spans some of which have ids and others don't.

Input:

<span>Hi there!</span><span id="blabla">This is a test</span>

Output:

Hi there!<span id="blabla">This is a test</span>

I prefer JavaScript functions but I wouldn't mind using jQuery if it makes things easier!

like image 350
Eyad Fallatah Avatar asked Dec 28 '22 11:12

Eyad Fallatah


2 Answers

You should be able to use a combination of the :not pseudo-selector, and a "has-attribute" selector:

$("span:not([id])").contents().unwrap();

Here's a working example. Notice how the HTML code is made up of 4 span elements, the CSS rule applies to all span elements, but does not apply to the 2 span elements without an id, because they have been unwrapped by the above jQuery.

The contents method returns all of the children of the selected elements, and unwrap removes the parent, which in this case will be the unwanted span.

like image 157
James Allardice Avatar answered Jan 14 '23 14:01

James Allardice


$("span").each(function(){
    if (this.id == "") $(this).replaceWith(this.innerHTML);
})

http://jsfiddle.net/qDR32/

like image 41
Cory Danielson Avatar answered Jan 14 '23 13:01

Cory Danielson