Replace image without ID/Class with JQuery
I'm applying an external theme via Google Chrome Extension for a website. The logo doesn't have an ID or a class to call it by and I'm looking for a way to replace it with another 开发者_如何学编程image. I feel like there may be a way to get the image based on its size, but I wouldn't know what to do from there.
if it's for example in <div id="something">
you can catch it with
$("#something img:first").attr('src', 'http://new.src/img.gif');
If you know what the file name of the linked image is you can select by that using the contains selector.
http://api.jquery.com/attribute-contains-word-selector/
$("img[src~='cats.gif']");
You need to first select an element close to it.
e.g. if it is the third child of the element with id example
:
$("#example :nth-child(3)").attr('src', '...');
or, if the parent element has no ID, you will have to do it using the direct child selector. If the HTML is:
<div id="myDiv">
<div>blah</div>
<div><img src="..."/></div>
</div>
Your selector would be:
$("#myDiv > div:nth-child(2) > img");
You should be able to call $("img:eq(1)").attr("src", "file.png");
Where 1
is the index of the image. As waitinforatrain points out below, this is zero-based. From the API entry:
Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $('.myclass:eq(1)') selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.
See :eq selector in the JQuery API for more information.
精彩评论