开发者

How can I select an HTML element from JavaScript without knowing its ID?

I have an unknown number 开发者_如何转开发of <img> elements on my page with no IDs, and I need to be able to browse through them and set certain attributes based on a number of unpredictable factors.


You would use this function to browse through them as an array:

document.getElementsByTagName('img');

This is an array of img elements, and you can treat it as if you were using the getElementById() function (i.e. you can still do the same operations on the elements, but you need to reference an element):

document.getElementsByTagName('img')[0]

If the factors you are speaking about are really complicated, I would use jQuery (it's really powerful):

$('img[alt]').css('padding', '10px');

This would add a 10px padding to every image with an alt attribute (I hope, as I'm notorious for posting almost-working code).

Good luck!


Everyone forgets about document.images...

for(var i = 0; i < document.images.length; i++) {
  var img = document.images[i];

  if(img.src == "banner.gif") {
     img.alt = "Banner";
  }
  else if(img.alt == "Giraffe") {
     img.title = "15 feet tall!";
  }
}

If you need to get images within another element, you can use getElementsByTagName...

var elem = document.getElementById('foo');
var fooImages = elem.getElementsByTagName('img');


Use document.getElementsByTagName():

var imgs = document.getElementsByTagName("img");

for(var i = 0; i < imgs.length; i++) {
   var currentImg = imgs[i];
   if (currentImg.somAttr) {
       // do your stuff
   }
}


You can use getElementsByTagName to get a list of the img tags:

https://developer.mozilla.org/en/DOM/element.getElementsByTagName


You can set name attribue for image tag and can perform any operation using document.getElementsByName.

for example

<script type="text/javascript">
function getElements()
  {
  var x=document.getElementsByName("x");
  alert(x.length);
  }
</script>

<input name="x" type="text" size="20" /><br />
<input name="x" type="text" size="20" />


Use jQuery and search by element type $("img").each() to perform am operation on each element


jQuery is probably your best bet. Otherwise you'll have to traverse a dom tree and check for attributes manually. Once you use jQuery you can select elements by attributes like name, class, the tag name (input, image, etc) and combinations of them.

$("image .className").attr(....

http://www.jquery.com


It's hard to answer this without knowing more specifics, but have you considered using Jquery?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜