0

Lets say i have an Image in my html that has no id or class like:

<img title="me" src="something_blabla_nonactive">

and i want it to Change to

<img title="me" src="something_blabla_active">

when the page loads, how do i do that in JS?

Thanks in advance!

Mella
  • 35
  • 1
  • 11
  • Your options in order from the best to worst: 1. add id or class. 2. select image based on surrounding/parent elements. 3. select image by title attribute. The last one really sucks though. – dfsq Mar 15 '17 at 14:10

3 Answers3

2

Use querySelector to get the first one like this:

var firstImg = document.querySelector('img[title="me"]');

Or querySelectorAll to get an array-like object of all the images that have the title attribute set to me like this:

var allImgs = document.querySelectorAll('img[title="me"]');

The selector [title="me"] is the CSS Attribute-Equal Selector, here is a reference of all CSS Selectors.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Bhuwan
  • 177
  • 2
  • 12
-1

Use this:

$('img[title="me"]').attr("src", "something_blabla_activ")
morten.c
  • 3,414
  • 5
  • 40
  • 45
Ajay
  • 196
  • 2
  • 12
  • This works great, but i just noticed that i have an mouseover image inside the img tag that needs to be changed as well, how do i do that? `code` – Mella Mar 15 '17 at 14:28
  • Simply add $( 'img[title="me"]' ).hover( function() { $( this )..attr("src", "something_blabla_hover-image"); }, function() { $( this )..attr("src", "something_blabla_after-hover"); } ); – Ajay Mar 15 '17 at 14:35
  • That somehow doesnt work and breaks the first Code, too. Thats what i have now: `code` jQuery('img[title="me"]').attr("src", "replaced.png");  jQuery( 'img[title="BRANDImpact"]' ).hover( function() { $( this )..attr("src", "hover.png"); }, function() { $( this )..attr("src", "replacedhover"); } ); Also, i Need the same replace function for the mouseout handler which is also inside the img. – Mella Mar 15 '17 at 14:56
  • remove mouseover and mouseout from img.... and use $( 'img[title="me"]' ).hover( function() { $( this ).attr("src", "mouseover-image"); }, function() { $( this ).attr("src", "mouseout-image"); } ); – Ajay Mar 15 '17 at 15:05
  • I cant, because this is generated by a wordpress plugin that Shows Images instead of menu text. :-( (The whole reason why i Need to replace Images is because i cant get Wordpress to set a specific menu item as active for Portfolio pages). – Mella Mar 15 '17 at 15:15
  • sorry for late... $('img[title="me"]').attr({"src": "something_blabla_activ", "mouseover": " ", "mouseout": ""}) add this on page load then hover effect work – Ajay Mar 16 '17 at 16:21
  • sorry for late as well, much apprecciated! – Mella Mar 22 '17 at 12:59
-1
 $('img[title=blah]') 

try this one.

Sagar V
  • 12,158
  • 7
  • 41
  • 68
Knj
  • 61
  • 7