0

Is there simple any way to get an element's starting tag in javascript as string? Suppose I have a DOM node which is a html element in a variable, I would like write something similar:

var tagName = element.tagName; //Works
var startingTag = element.startingTag; // Is there any way?
var startingTag = getStartingTag(element);  // Or do I have to write my own function?

Thx for answers

For example this is a starting tag I would like to get into a string:

 <Table class="anyClass" width="100" ... >

where the tagName only gives this: "Table"

Ian
  • 50,146
  • 13
  • 101
  • 111
g.pickardou
  • 32,346
  • 36
  • 123
  • 268
  • Is there a reason you need the full starting tag? To get the attributes? Maybe there's a different way to accomplish what you need – Ian Jan 25 '13 at 08:02
  • I need the starting tag as textual information to display in the user interface. I know how to get a specific attribute with DOM – g.pickardou Jan 25 '13 at 08:03
  • You could get all the attributes of the element, iterate through them (and their values) and construct the string manually. I don't know how difficult this would be in your situation. Should be right up your alley. – Adrian Marinica Jan 25 '13 at 08:04
  • 1
    i dont think there is default support to achieve what you want, you can how ever append a function startingTag to the element object vs building a standalone global function – Billybonks Jan 25 '13 at 08:08

2 Answers2

1

Well, you could do:

var elStr    = element.outerHTML
   ,startTag = elStr.substr(0,elStr.indexOf('>')+1);

Or use the element.attributes if you need information about attributes

KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

You can loop through the attributes and append them to some string.

function getStartingTag(elem)
    var str = '',
        attr = elem.attributes,
        value;

    // Beginning of tag. toLowerCase() for a cleaner string.
    str += '<' + elem.nodeName.toLowerCase() + ' ';

    for (var i = 0, l = attr.length; i < l; i++) {

        // Safety check.
        value = attr[i].nodeValue.replace('"', '\\"');

        // Append the name + value of the attribute.
        str += attr[i].nodeName + '="' + attr[i].nodeValue + '" ';
    }
    str += '>';

    return str;
}
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116