Say I have the following html:
<div id="myDiv" title="My Div">This is me!</div>
I want to write a jquery statement such that the result is the entire line above as a string.
I almost want something like:
var selectedHtml = $("#myDiv").self();
(I know that's not valid jquery) which results in selectedHtml
having the value "<div id="myDiv" title="My Div">This is me!</div>
"
Any ideas about which jquery function I'm looking for?
PS: getting the .html()
of this node's .parent()
will not work as it will give me siblings of the above node too.
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.
You could use $('. gettext'). text(); in jQuery.
Three simple, but useful, jQuery methods for DOM manipulation are: text() - Sets or returns the text content of selected elements. html() - Sets or returns the content of selected elements (including HTML markup) val() - Sets or returns the value of form fields.
I think might also be possible:
wrap
your div with another div (<div id="wrapdiv" />
) --> wrap()
html
on the wrapdiv unwrap
the wrapdiv (so do $("#myDiv").unwrap()
) --> unwrap()
Here is a live example: http://jsbin.com/oniki/edit
edit:
Perhaps this is better because it doesn't use an id for the wrapperdiv and therefore less change for bugs with existing ids:
wrap()
your div with another (nameless) divhtml()
of the parent()
of your divunwrap()
your divSee it in action: http://jsbin.com/oniki/3/edit
You can use plain javascript to do this.
var selectedHtml = document.getElementById ( "myDiv" ).outerHTML; //IE only
You can use this to get the outerHTML of a jquery element
jQuery.fn.outerHTML = function() {
return $('<div>').append( this.eq(0).clone() ).html();
};
From
jQuery Snippets: outerHTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With