Skip to content Skip to sidebar Skip to footer

JS - Document.getelementbysrc?

Is it possible to get an element from the value of the 'src' attribute?

Solution 1:

There is no DOM method to filter elements by attributes. You need to go through all the elements of a particular tag and filter out those with a matching src value:

function getElementsBySrc(srcValue) {
  var nodes = [];
  var e = document.getElementsByTagName('img');

  for (var i = 0; i < e.length; i++) {
    if (e[i].hasAttribute('src') && e[i].getAttribute('src') == srcValue) {
      nodes.push(e[i]);
    }
  }

  return nodes;
}

The nodes array will contain all the img elements with a src attribute that has a value image.png.


UPDATE:

Further to the comment below, keep in mind that there might be more than one element with the same src value. That is why the function above returns an array.

You can use the element.setAttribute() method to change the value of an attribute:

var n = getElementsBySrc('old-image.png');

for (var i = 0; i < n.length; i++) {
  n[i].setAttribute('src', 'new-image.png');
}

Solution 2:

I found some code when google:

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}

Source: http://snipplr.com/view/1853/get-elements-by-attribute/


Solution 3:

AFAIK (As Far As I Know) there is no native method to get the an element from the value of the src attribute. But using a JavaScript library you can achieve this in one line.

If you use jQuery, you can get the element writing the following code:

var elem = $('[src="path/to/something.xyz"]');

More documentation about this previous code in the jQuery doc.


Post a Comment for "JS - Document.getelementbysrc?"