Reputation: 1948
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
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
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
Reputation: 221
$("span").each(function (i) {
if (this.id == '') {
alert('no have id');
} else {
alert('have id');
}
});
Upvotes: 1
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
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
Reputation: 14501
$("span").each(function(){
if (this.id == "") $(this).replaceWith(this.innerHTML);
})
Upvotes: 1