سؤال

كيف تقوم بتحويل كائن jQuery إلى سلسلة؟

هل كانت مفيدة؟

المحلول

أفترض أنك تطلب سلسلة HTML الكاملة. إذا كان هذا هو الحال ، فإن شيئًا كهذا سيفعل الخدعة:

$('<div>').append($('#item-of-interest').clone()).html(); 

يتم شرح هذا بتعمق أكبر هنا, ، ولكن في الأساس تقوم بإنشاء عقدة جديدة لالتفاف عنصر الاهتمام ، والقيام بالتلاعب ، وإزالته ، والاستيلاء على HTML.

إذا كنت بعد تمثيل السلسلة ، فانتقل مع new String(obj).

تحديث

كتبت الإجابة الأصلية في عام 2009. اعتبارًا من عام 2014 ، تدعم معظم المتصفحات الرئيسية الآن outerHTML كعقار أصلي (انظر ، على سبيل المثال ، ثعلب النار و متصفح الانترنت) ، حتى تتمكن من فعل:

$('#item-of-interest').prop('outerHTML');

نصائح أخرى

مع jQuery 1.6 ، يبدو أن هذا حل أكثر أناقة:

$('#element-of-interest').prop('outerHTML');

Just use .get(0) to grab the native element, and get its outerHTML property:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);

Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:

HTML snippet:

<p><b>This is some text</b></p>

jQuery:

var txt = $('p').html(); // Value of text is <b>This is some text</b>

The best way to find out what properties and methods are available to an HTML node (object) is to do something like:

console.log($("#my-node"));

From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:

var node = $("#my-node").outerHTML;

jQuery is up in here, so:

jQuery.fn.goodOLauterHTML= function() {
    return $('<a></a>').append( this.clone() ).html();
}

Return all that HTML stuff:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all

This seems to work fine for me:

$("#id")[0].outerHTML

The accepted answer doesn't cover text nodes (undefined is printed out).

This code snippet solves it:

var htmlElements = $('<p><a href="http://google.com">google</a></p>↵↵<p><a href="http://bing.com">bing</a></p>'),
    htmlString = '';
    
htmlElements.each(function () {
    var element = $(this).get(0);

    if (element.nodeType === Node.ELEMENT_NODE) {
        htmlString += element.outerHTML;
    }
    else if (element.nodeType === Node.TEXT_NODE) {
        htmlString += element.nodeValue;
    }
});

alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

No need to clone and add to the DOM to use .html(), you can do:

$('#item-of-interest').wrap('<div></div>').html()

It may be possible to use the jQuery.makeArray(obj) utility function:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];

If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:

// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')

// now 'e_str' is a unique query for this element that can be stringify 
var e_str = e.tagName
  + ( e.id != "" ? "#" + e.id : "")
  + ( e.className != "" ? "." + e.className.replace(' ','.') : "");

//now you can stringify your element to JSON string
var e_json = JSON.stringify({
  'element': e_str
})

than

//parse it back to an object
var obj = JSON.parse( e_json )

//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )

//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
new String(myobj)

If you want to serialize the whole object to string, use JSON.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top