web-dev-qa-db-ja.com

Javascript / jQueryを使用してHTML要素からすべての属性を取得する

Html要素のすべての属性を配列に入れたい:jQueryオブジェクトがあるように、これはhtmlのように見える:

<span name="test" message="test2"></span>

今の方法の1つは、 here で説明されているxmlパーサーを使用することですが、それからオブジェクトのhtmlコードを取得する方法を知る必要があります。

もう1つの方法はjqueryで作成することですが、どのようにですか?属性の数と名前は一般的です。

ありがとう

Btw:document.getelementbyidまたは類似のもので要素にアクセスできません。

158
k0ni

DOM属性だけが必要な場合は、おそらく要素自体でattributesノードリストを使用する方が簡単です。

var el = document.getElementById("someId");
for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){
    arr.Push(atts[i].nodeName);
}

これは、属性名のみで配列を埋めることに注意してください。属性値が必要な場合は、nodeValueプロパティを使用できます。

var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
    att = atts[i];
    nodes.Push(att.nodeName);
    values.Push(att.nodeValue);
}
202
Roland Bouman

このシンプルなプラグインは$( '#some_id')。getAttributes();として使用できます。

(function($) {
    $.fn.getAttributes = function() {
        var attributes = {}; 

        if( this.length ) {
            $.each( this[0].attributes, function( index, attr ) {
                attributes[ attr.name ] = attr.value;
            } ); 
        }

        return attributes;
    };
})(jQuery);
70
manRo

シンプル:

var element = $("span[name='test']");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
55
Aki143S

IE7では、elem.attributesには現在の属性だけでなく、可能なすべての属性がリストされているため、属性値をテストする必要があります。このプラグインは、すべての主要なブラウザーで機能します。

(function($) {
    $.fn.getAttributes = function () {
        var elem = this, 
            attr = {};

        if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) { 
            n = n.nodeName||n.name;
            v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
            if(v != undefined && v !== false) attr[n] = v
        })

        return attr
    }
})(jQuery);

使用法:

var attribs = $('#some_id').getAttributes();
19
DUzun

セッターとゲッター!

(function($) {
    // Attrs
    $.fn.attrs = function(attrs) {
        var t = $(this);
        if (attrs) {
            // Set attributes
            t.each(function(i, e) {
                var j = $(e);
                for (var attr in attrs) {
                    j.attr(attr, attrs[attr]);
                }
            });
            return t;
        } else {
            // Get attributes
            var a = {},
                r = t.get(0);
            if (r) {
                r = r.attributes;
                for (var i in r) {
                    var p = r[i];
                    if (typeof p.nodeValue !== 'undefined') a[p.nodeName] = p.nodeValue;
                }
            }
            return a;
        }
    };
})(jQuery);

つかいます:

// Setter
$('#element').attrs({
    'name' : 'newName',
    'id' : 'newId',
    'readonly': true
});

// Getter
var attrs = $('#element').attrs();
18
Eduardo Cuomo

.sliceを使用して、attributesプロパティを配列に変換します

DOMノードのattributesプロパティは NamedNodeMap で、これは配列のようなオブジェクトです。

Arrayのようなオブジェクトは、lengthプロパティを持ち、プロパティ名が列挙されているが、それ以外の場合は独自のメソッドを持ち、 Array.prototype から継承しないオブジェクトです。

sliceメソッドを使用して、配列のようなオブジェクトを新しい配列に変換できます

var elem  = document.querySelector('[name=test]'),
    attrs = Array.prototype.slice.call(elem.attributes);

console.log(attrs);
<span name="test" message="test2">See console.</span>
6
gfullam

このアプローチは、配列で返されるオブジェクトの名前と値を持つすべての属性を取得する必要がある場合に有効です。

出力例:

[
    {
        name: 'message',
        value: 'test2'
    }
    ...
]
function getElementAttrs(el) {
  return [].slice.call(el.attributes).map((attr) => {
    return {
      name: attr.name,
      value: attr.value
    }
  });
}

var allAttrs = getElementAttrs(document.querySelector('span'));
console.log(allAttrs);
<span name="test" message="test2"></span>

その要素の属性名の配列のみが必要な場合は、結果をマッピングするだけです。

var onlyAttrNames = allAttrs.map(attr => attr.name);
console.log(onlyAttrNames); // ["name", "message"]
2
KevBot

Roland Boumananswer は、最高のシンプルなバニラの方法です。 jQプラグの試みに気づきましたが、それらは私には十分に「いっぱい」に見えなかったので、自分で作りました。これまでの唯一の失敗は、Elm.attr('dynamicAttr')を直接呼び出さずに動的に追加されたattrにアクセスできなかったことです。ただし、これはjQuery要素オブジェクトのすべての自然属性を返します。

プラグインは、単純なjQueryスタイルの呼び出しを使用します。

$(Elm).getAttrs();
// OR
$.getAttrs(Elm);

特定の属性を1つだけ取得するために、2番目の文字列パラメーターを追加することもできます。 jQueryはすでに$(Elm).attr('name')を提供しているため、これは1つの要素選択には実際には必要ありませんが、プラグインの私のバージョンでは複数のリターンが可能です。したがって、たとえば、次のような呼び出し

$.getAttrs('*', 'class');

オブジェクト[]の配列{}が返されます。各オブジェクトは次のようになります。

{ class: 'classes names', Elm: $(Elm), index: i } // index is $(Elm).index()

プラグイン

;;(function($) {
    $.getAttrs || ($.extend({
        getAttrs: function() {
            var a = arguments,
                d, b;
            if (a.length)
                for (x in a) switch (typeof a[x]) {
                    case "object":
                        a[x] instanceof jQuery && (b = a[x]);
                        break;
                    case "string":
                        b ? d || (d = a[x]) : b = $(a[x])
                }
            if (b instanceof jQuery) {
                var e = [];
                if (1 == b.length) {
                    for (var f = 0, g = b[0].attributes, h = g.length; f < h; f++) a = g[f], e[a.name] = a.value;
                    b.data("attrList", e);
                    d && "all" != d && (e = b.attr(d))
                } else d && "all" != d ? b.each(function(a) {
                    a = {
                        Elm: $(this),
                        index: $(this).index()
                    };
                    a[d] = $(this).attr(d);
                    e.Push(a)
                }) : b.each(function(a) {
                    $elmRet = [];
                    for (var b = 0, d = this.attributes, f = d.length; b < f; b++) a = d[b], $elmRet[a.name] = a.value;
                    e.Push({
                        Elm: $(this),
                        index: $(this).index(),
                        attrs: $elmRet
                    });
                    $(this).data("attrList", e)
                });
                return e
            }
            return "Error: Cannot find Selector"
        }
    }), $.fn.extend({
        getAttrs: function() {
            var a = [$(this)];
            if (arguments.length)
                for (x in arguments) a.Push(arguments[x]);
            return $.getAttrs.apply($, a)
        }
    }))
})(jQuery);

順守

;;(function(c){c.getAttrs||(c.extend({getAttrs:function(){var a=arguments,d,b;if(a.length)for(x in a)switch(typeof a[x]){case "object":a[x]instanceof jQuery&&(b=a[x]);break;case "string":b?d||(d=a[x]):b=c(a[x])}if(b instanceof jQuery){if(1==b.length){for(var e=[],f=0,g=b[0].attributes,h=g.length;f<h;f++)a=g[f],e[a.name]=a.value;b.data("attrList",e);d&&"all"!=d&&(e=b.attr(d));for(x in e)e.length++}else e=[],d&&"all"!=d?b.each(function(a){a={Elm:c(this),index:c(this).index()};a[d]=c(this).attr(d);e.Push(a)}):b.each(function(a){$elmRet=[];for(var b=0,d=this.attributes,f=d.length;b<f;b++)a=d[b],$elmRet[a.name]=a.value;e.Push({Elm:c(this),index:c(this).index(),attrs:$elmRet});c(this).data("attrList",e);for(x in $elmRet)$elmRet.length++});return e}return"Error: Cannot find Selector"}}),c.fn.extend({getAttrs:function(){var a=[c(this)];if(arguments.length)for(x in arguments)a.Push(arguments[x]);return c.getAttrs.apply(c,a)}}))})(jQuery);

jsFiddle

/*  BEGIN PLUGIN  */
;;(function($) {
        $.getAttrs || ($.extend({
                getAttrs: function() {
                        var a = arguments,
                                c, b;
                        if (a.length)
                                for (x in a) switch (typeof a[x]) {
                                        case "object":
                                                a[x] instanceof f && (b = a[x]);
                                                break;
                                        case "string":
                                                b ? c || (c = a[x]) : b = $(a[x])
                                }
                        if (b instanceof f) {
                                if (1 == b.length) {
                                        for (var d = [], e = 0, g = b[0].attributes, h = g.length; e < h; e++) a = g[e], d[a.name] = a.value;
                                        b.data("attrList", d);
                                        c && "all" != c && (d = b.attr(c));
                                        for (x in d) d.length++
                                } else d = [], c && "all" != c ? b.each(function(a) {
                                        a = {
                                                Elm: $(this),
                                                index: $(this).index()
                                        };
                                        a[c] = $(this).attr(c);
                                        d.Push(a)
                                }) : b.each(function(a) {
                                        $elmRet = [];
                                        for (var b = 0, c = this.attributes, e = c.length; b < e; b++) a = c[b], $elmRet[a.name] = a.value;
                                        d.Push({
                                                Elm: $(this),
                                                index: $(this).index(),
                                                attrs: $elmRet
                                        });
                                        $(this).data("attrList", d);
                                        for (x in $elmRet) $elmRet.length++
                                });
                                return d
                        }
                        return "Error: Cannot find Selector"
                }
        }), $.fn.extend({
                getAttrs: function() {
                        var a = [$(this)];
                        if (arguments.length)
                                for (x in arguments) a.Push(arguments[x]);
                        return $.getAttrs.apply($, a)
                }
        }))
})(jQuery);
/*  END PLUGIN  */
/*--------------------*/
$('#bob').attr('bob', 'bill');
console.log($('#bob'))
console.log(new Array(50).join(' -'));
console.log($('#bob').getAttrs('id'));
console.log(new Array(50).join(' -'));
console.log($.getAttrs('#bob'));
console.log(new Array(50).join(' -'));
console.log($.getAttrs('#bob', 'name'));
console.log(new Array(50).join(' -'));
console.log($.getAttrs('*', 'class'));
console.log(new Array(50).join(' -'));
console.log($.getAttrs('p'));
console.log(new Array(50).join(' -'));
console.log($('#bob').getAttrs('all'));
console.log($('*').getAttrs('all'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
All of below is just for stuff for plugin to test on. See developer console for more details.
<hr />
<div id="bob" class="wmd-button-bar"><ul id="wmd-button-row-27865269" class="wmd-button-row" style="display:none;">
<div class="post-text" itemprop="text">
<p>Roland Bouman's answer is the best, simple Vanilla way. I noticed some attempts at jQ plugs, but they just didn't seem "full" enough to me, so I made my own. The only setback so far has been inability to access dynamically added attrs without directly calling <code>Elm.attr('dynamicAttr')</code>. However, this will return all natural attributes of a jQuery element object.</p>

<p>Plugin uses simple jQuery style calling:</p>

<pre class="default prettyprint prettyprinted"><code><span class="pln">$</span><span class="pun">(</span><span class="pln">Elm</span><span class="pun">).</span><span class="pln">getAttrs</span><span class="pun">();</span><span class="pln">
</span><span class="com">// OR</span><span class="pln">
$</span><span class="pun">.</span><span class="pln">getAttrs</span><span class="pun">(</span><span class="pln">Elm</span><span class="pun">);</span></code></pre>

<p>You can also add a second string param for getting just one specific attr. This isn't really needed for one element selection, as jQuery already provides <code>$(Elm).attr('name')</code>, however, my version of a plugin allows for multiple returns. So, for instance, a call like</p>

<pre class="default prettyprint prettyprinted"><code><span class="pln">$</span><span class="pun">.</span><span class="pln">getAttrs</span><span class="pun">(</span><span class="str">'*'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'class'</span><span class="pun">);</span></code></pre>

<p>Will result in an array <code>[]</code> return of objects <code>{}</code>. Each object will look like:</p>

<pre class="default prettyprint prettyprinted"><code><span class="pun">{</span><span class="pln"> </span><span class="kwd">class</span><span class="pun">:</span><span class="pln"> </span><span class="str">'classes names'</span><span class="pun">,</span><span class="pln"> Elm</span><span class="pun">:</span><span class="pln"> $</span><span class="pun">(</span><span class="pln">Elm</span><span class="pun">),</span><span class="pln"> index</span><span class="pun">:</span><span class="pln"> i </span><span class="pun">}</span><span class="pln"> </span><span class="com">// index is $(Elm).index()</span></code></pre>
    </div>
  </div>
2
SpYk3HH

より簡潔な方法:

古い方法(IE9 +):

var element = document.querySelector(/* … */);
[].slice.call(element.attributes).map(function (attr) { return attr.nodeName; });

ES6の方法(エッジ12以降):

[...document.querySelector(/* … */).attributes].map(attr => attr.nodeName);
  • document.querySelector() は、指定されたセレクターに一致するドキュメント内の最初の Element を返します。
  • Element.attributes は、対応するHTML要素の割り当てられた属性を含む NamedNodeMap オブジェクトを返します。
  • [].map() は、呼び出し配列内のすべての要素で提供された関数を呼び出した結果で新しい配列を作成します。

デモ:

console.log(
  [...document.querySelector('img').attributes].map(attr => attr.nodeName)
);
/* Output console formatting */
.as-console-wrapper { position: absolute; top: 0; }
<img src="…" alt="…" height="…" width="…"/>
1
Przemek

これは役立ちますか?

このプロパティは、要素のすべての属性を配列に返します。以下に例を示します。

window.addEventListener('load', function() {
  var result = document.getElementById('result');
  var spanAttributes = document.getElementsByTagName('span')[0].attributes;
  for (var i = 0; i != spanAttributes.length; i++) {
    result.innerHTML += spanAttributes[i].value + ',';
  }
});
<span name="test" message="test2"></span>
<div id="result"></div>

多くの要素の属性を取得して整理するには、ループするすべての要素の配列を作成し、ループする各要素のすべての属性のサブ配列を作成することをお勧めします。

これは、収集された要素をループし、2つの属性を出力するスクリプトの例です。このスクリプトは、常に2つの属性があることを前提としていますが、さらにマッピングすることで簡単に修正できます。

window.addEventListener('load',function(){
  /*
  collect all the elements you want the attributes
  for into the variable "elementsToTrack"
  */ 
  var elementsToTrack = $('body span, body div');
  //variable to store all attributes for each element
  var attributes = [];
  //gather all attributes of selected elements
  for(var i = 0; i != elementsToTrack.length; i++){
    var currentAttr = elementsToTrack[i].attributes;
    attributes.Push(currentAttr);
  }
  
  //print out all the attrbute names and values
  var result = document.getElementById('result');
  for(var i = 0; i != attributes.length; i++){
    result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'<br>';  
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div id="result"></div>
1
www139

ここのすべての答えには、 getAttributeNames elementメソッドを使用した最も簡単なソリューションがありません!

すべての要素の現在の属性の名前を通常の配列として取得し、キー/値のNiceオブジェクトに縮小できます。

const getAllAttributes = el => el
  .getAttributeNames()
  .reduce((obj, name) => ({
    ...obj,
    [name]: el.getAttribute(name)
  }), {})

console.log(getAllAttributes(document.querySelector('div')))
<div title="hello" className="foo" data-foo="bar"></div>
0
Tim Kindberg
Element.prototype.getA = function (a) {
        if (a) {
            return this.getAttribute(a);
        } else {
            var o = {};
            for(let a of this.attributes){
                o[a.name]=a.value;
            }
            return o;
        }
    }

<div id="mydiv" a='1' b='2'>...</div>を使用できる

mydiv.getA() // {id:"mydiv",a:'1',b:'2'}
0
bortunac

このようなものを試してください

    <div id=foo [href]="url" class (click)="alert('hello')" data-hello=world></div>

そして、すべての属性を取得します

    const foo = document.getElementById('foo');
    // or if you have a jQuery object
    // const foo = $('#foo')[0];

    function getAttributes(el) {
        const attrObj = {};
        if(!el.hasAttributes()) return attrObj;
        for (const attr of el.attributes)
            attrObj[attr.name] = attr.value;
        return attrObj
    }

    // {"id":"foo","[href]":"url","class":"","(click)":"alert('hello')","data-hello":"world"}
    console.log(getAttributes(foo));

属性の配列用

    // ["id","[href]","class","(click)","data-hello"]
    Object.keys(getAttributes(foo))
0
weroro

次のようなHTML要素があると想像してください。

<a class="toc-item"
   href="/books/n/ukhta2333/s5/"
   id="book-link-29"
>
   Chapter 5. Conclusions and recommendations
</a>

すべての属性を取得する1つの方法は、それらを配列に変換することです。

const el = document.getElementById("book-link-29")
const attrArray = Array.from(el.attributes)

// Now you can iterate all the attributes and do whatever you need.
const attributes = attrArray.reduce((attrs, attr) => {
    attrs !== '' && (attrs += ' ')
    attrs += `${attr.nodeName}="${attr.nodeValue}"`
    return attrs
}, '')
console.log(attributes)

そして、以下は、すべての属性を含む(例から)取得する文字列です。

class="toc-item" href="/books/n/ukhta2333/s5/" id="book-link-29"
0
Yuci