Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the full definition of the HTML tag using Jquery?

Tags:

html

jquery

css

To get the tag name in JQuery, we use:

     $(someCssSelector).prop('tagName');

This returns the tag name, e.g. 'DIV', 'TABLE'

How do I get the entire tag definition with all attributes, other than iterating over the element and getting each attribute's value? I need the text of the definition. For example:

<div id="myDiv" style="...." title="....">....</div>

Given the CSS selector for any element, I want to get, as string:

<div id="myDiv" style="...."  title="....">

The order of the attributes in the output string is not important.

like image 257
asinix Avatar asked Dec 09 '25 09:12

asinix


1 Answers

One option is to check the element's outerHTML, and match the < to the >:

const openingHtmlTag = $('#myDiv')[0]
  .outerHTML
  .match(/<[^>]+>/)[0];
console.log(openingHtmlTag);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="myDiv" style="color:green" title="foobar">content<div>

Or, in the somewhat unusual case that an attribute property can contain >s and escaped quotes, the regular expression needs to be expanded:

const re = /^<(?:[^'">]*|(['"])(?:\\.|(?!\1).)*\1)+>/s;
const openingHtmlTag = $('#myDiv')[0]
  .outerHTML
  .match(re)[0];
console.log(openingHtmlTag);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="myDiv" style="color:green" title="foobar">content<div>

https://regex101.com/r/OBNoBa/1

^<(?:[^'">]*|(['"])(?:\\.|(?!\1).)*\1)+> means:

  • ^< - Start of string, followed by < (start of the opening tag)
  • (?:[^'">]*|(['"])(?:\\.|(?!\1).)*\1)+ - Repeat 1+ times:
    • [^'">]* - Anything but quotes or an closing bracket, OR:
    • (['"])(?:\\.|(?!\1).)*\1 A quoted attribute:
    • (['"]) - Opening string delimiter, first capture group. Then repeatedly match either:
      • \\. - Any escaped character (this allows, eg, \' to be matched, rather than the ' being interpreted as the closing string delimiter), OR
      • (?!\1). - Anything but the string delimiter
    • \1 - The string delimiter again (end of the quoted attribute)
  • > - Closure of the opening tag

Another option would be to shallow clone the node (thus omitting any children it may have), take its outerHTML, and strip off the closing tag (which is a lot easier to match):

const re = /^<(?:[^'">]*|(['"])(?:\\.|(?!\1).)*\1)+>/s;
const cloned = $('#myDiv')[0].cloneNode(false);
const html = cloned.outerHTML.replace(/<\s*\/\w+\s*>$/, '');
console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="myDiv" style="color:green" title="foobar">content<div>
like image 115
CertainPerformance Avatar answered Dec 11 '25 00:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!