Reputation: 327
Say I have the following:
<div id="myid" class="myclass"></div>
What I would like to do is find this tag via jQuery and get the stuff between <> for this div. In this case I would like for my output to be as follows:
div id="myid" class="myclass"
Not looking for innerHTML, just what's in the tag. I know I can use jQuery to test for known attributes, but I'm really looking to be able to get the actual string here. It occurred to me that I could get the innerHTML of a parent tag and then do some parsing, but that seems messy and error prone. I would much rather be able to do something like the following
alert($('#myid').getTagContents())
and have it alert the bit above. Is this possible? Any idea on how to do it?
FYI, I see that this question has been marked as a duplicate, but the other question does not address my concerns. I don't want to loop through attributes. I want the literal string from the tag, so I can parse it myself.
Upvotes: 2
Views: 69
Reputation: 674
This should retrieve what you want.
alert($('#myId')[0].outerHTML.split('>')[0].substring(1));
Upvotes: 3
Reputation: 66981
You basically need to build something yourself. Made a real quick jQuery extension that returns the result.
$.fn.getTagContents = function () {
var $this = $(this),
tags = $this[0].outerHTML,
endLoc = '';
endLoc = tags.indexOf('>') - 1;
return tags.substr(1, endLoc);
};
var tags = $('#test').getTagContents();
console.log(tags);
// logs: div id="test" class="whatever"
Upvotes: 1