Javascript for markup without id

Is it possible to find and not specify spaces that do not have identifiers inside the string? I have text with many runs, some of which have identifiers, and others not.

Entrance:

<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 would not mind using jQuery if this makes your work easier.

+4
source share
6 answers

You must use a combination of :not pseudo selector and has-attribute "Selector:

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

Here is a working example . Please note that the HTML code consists of 4 span elements, the CSS rule applies to all span elements, but does not apply to 2 span elements without id , since they were deployed using jQuery.

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

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

http://jsfiddle.net/qDR32/

+1
source
 $("span").each(function (i) { if (this.id == '') { alert('no have id'); } else { alert('have id'); } }); 
+1
source

Using jQuery would be very simple.

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

See a working example here ..

+1
source

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 functional 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/

+1
source

There is a clean 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); } }); 

Doing this work in browsers that don't have Array.prototype.forEach is left to the user to read.

+1
source

Source: https://habr.com/ru/post/1381216/


All Articles