Domanda

The case : should select object

example:

function getDomPart(text,htmlTag){
    return $(text).closest(htmlTag).get(0);
}

var text1='<object>some text + html elements  </object>';
var text2='<div><object>some text + html elements  </object></div>';
alert(getDomPart(text1,'object'));
alert(getDomPart(text2,'object'));

the result should be: some text + html elements but its not.

please tell me what should be fixed.

Edit: please see my answer with short solution.

È stato utile?

Soluzione 3

The solution that i get idea about : add wrapper element then can be used only find :

function search(text,htmlTag){
    return  $('<div>'+text+'</div>').find(htmlTag).html();
}


var text1='<object>some text + html elements  </object>';
var text2='<div><object>some text + html elements  </object></div>';
alert(search(text1,'object'));
alert(search(text2,'object'));

Demo: http://jsfiddle.net/EaZrs/5/

Altri suggerimenti

closest is searching the DOM up, not down like find.

closest docs:

Description: Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

find docs:

Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

so for text1 it should be closest and for text2 it should be find :

function getDomPartUp(text,htmlTag){
    return $(text).closest(htmlTag).html();
}

function getDomPartDown(text,htmlTag){
    return $(text).find(htmlTag).html();
}

var text1='<object>some text + html elements  </object>';
var text2='<div><object>some text + html elements  </object></div>';
alert(getDomPartUp(text1,'object'));
alert(getDomPartDown(text2,'object'));​

Use .html to get the text you wanted.

JSFiddle DEMO


Update:

To do it in one method:

function search(text,htmlTag){
    var $up = $(text).closest(htmlTag);

    if ($up.length > 0)
        return $up.html();

    var $down = $(text).find(htmlTag);

    return $down.length > 0 ? $down.html() :"";
}    

var text1='<object>some text + html elements  </object>';
var text2='<div><object>some text + html elements  </object></div>';
alert(search(text1,'object'));
alert(search(text2,'object'));​

JSFiddle DEMO

Try to use find() for the element's children and andSelf() to get the element itself.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top