Eyad Fallatah
Eyad Fallatah

Reputation: 1948

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!

Upvotes: 4

Views: 216

Answers (6)

Šime Vidas
Šime Vidas

Reputation: 185933

Here you go:

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

output = $( '<div>' ).html( input ).children().each( function () {
   !this.id && $( this ).replaceWith( $( this ).text() );
}).end().html();

Live demo: http://jsfiddle.net/3EXkh/3/


Update: The above code in function-form:

function untag( input ) {
    return $( '<div>' ).html( input ).children().each( function () {
       !this.id && $( this ).replaceWith( $( this ).text() );
    }).end().html();
} 

Live demo: http://jsfiddle.net/3EXkh/4/

Upvotes: 1

s4y
s4y

Reputation: 51685

Here’s a pure-JavaScript solution, FWIW:

Array.prototype.forEach.call(el.getElementsByTagName('span'), function(element){
    var children;
    if( ! element.id){
        children = document.createDocumentFragment();
        while(element.firstChild){
            children.appendChild(element.firstChild);
        }
        element.parentElement.replaceChild(children, element);
    }
});

Making this work in browsers which don’t have Array.prototype.forEach is left as en exercise for the reader.

Upvotes: 1

id1
id1

Reputation: 221

$("span").each(function (i) {

 if (this.id == '') {

  alert('no have id');

 } else {

  alert('have id');
 }

});

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23054

Using jQuery this would be very straightforward.

$(function(){
    $('span').each(function(){
        if(typeof $(this).attr('id') == "undefined"){
            $(this)[0].outerHTML = $(this).html();
        }
    });
});

See working example here..

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

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.

Upvotes: 5

Cory Danielson
Cory Danielson

Reputation: 14501

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

http://jsfiddle.net/qDR32/

Upvotes: 1

Related Questions