Change part of a string with jQuery - javascript

I'm sure this is something simple, but I can't figure it out.
I have this HTML:
<img src="/7290/9200572193_f95fb66c50_m.jpg" />
Which I need to change to
<img src="/7290/9200572193_f95fb66c50_b.jpg" />
This isn't always the same image, but the _m.jpg and _b.jpg are. How can I do this with jQuery?

You can do:
var imgSrc = "/7290/9200572193_f95fb66c50_m.jpg";
imgSrc = imgSrc.replace("_m.jpg", "_b.jpg");

Something like this may help you:
$( "img" ).each(function() {
var src = $( this ).attr( "src" );
$( this ).attr( "src", src.replace( /_m\.(.*)$/, "_b.$1" ) );
});
This will not depend on the extension of your src attribute.

Loop through "img" tags with $("img").each(function(){ doStuff(); });. Change attributes with attr("attribute","new_value"), get attributes with attr("attribute"). Replace with replace("from","to").
$("img").each(function(){
$(this).attr("src",$(this).attr("src").replace("_m","_b"));
});

In short, use.replace. Such as:
"/7290/9200572193_f95fb66c50_m.jpg".replace('_m.jpg', '_b.jpg');
/* OR */
var url = "/7290/9200572193_f95fb66c50_m.jpg";
url.replace('_m.jpg', '_b.jpg');
You use .each() in jQuery to loop through a group of elements. Thus you can use a simple selector like $('img') to select all images on the view and then make changes in the callback method. You would then use .prop to both set and get the current src and change it using old fashioned .replace
$("img").each(function(i) {
$(this).prop("src", $(this).prop("src").replace('_m.jpg', '_b.jpg'));
});
Example

Related

jquery random element id for every loop

sorry i'm new in jquery and i need help :-(
i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)
for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:
$(document).ready(function() {
$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);
$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );
});
});
$(".anot-body") does a search of the whole document, if you want to find a particular element in another element you need to do a search from that parent element.
In your case you would do a search on the particular .parts element that is currently being iterated over in your $.each() callback
$('.parts').each(function(index,element){
var parent = $(element);
var ran=Math.floor(Math.random()* 1000000);
parent.find('.anot-head').attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
parent.find('.anot-body').attr( "id","s"+ran );
});
No need to use random.... use index of each
$('.parts').each(function(index){
var $part = $(this);
$part.find('.anot-head').attr({"data-toggle":"collapse","href":"#s"+index});
$part.find('.anot-body').attr("id","s"+ index);
});

Wrap a tag around href inside a div

In the HTML code there is a 'href' , is there any posiblity to wrap an A-tag() around it? I'm new to this so please don't be too harsh :)
Note that the jquery is there to find the 'href' of a child inside the div and setting that attritbute to .summary-item-wrapper
HTML:
<div class="summary-item-wrapper" href="www.google.no" id="yui_3_17_2_4_1483527702805_1738"><div>
Jquery:
$(document).ready(function(){
$('body').wrapInner('<div id="support"></div>');
$('#support .sqs-block-summary-v2 .summary-item').each(function () {
var linkto = $(this).find('.summary-title a').attr('href');
$(this).children('.summary-item-wrapper').attr('href', linkto);
});
});
If there are multiple divs on your page you wish to convert, and to remove divs, but to keep all attributes, you can do something like this:
$( "div.summary-item-wrapper" ).each(function() {
$(this).before('<a href=http://'+$(this).attr('href') +'>A link');
$(this).prev().attr('id',$(this).attr('id'));
$(this).prev().addClass($(this).attr('class'));
});
$('div.summary-item-wrapper').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="summary-item-wrapper" href="www.google.no" id="yui_3_17_2_4_1483527702805_1738">44444444444</div>
<div class="summary-item-wrapper" href="www.google.com" id="yui_3_17_2_4_1483527702805_33333">ttttttttttt</div>
What you want can be done with this:
$('#support .sqs-block-summary-v2 .summary-item-wrapper').wrap(function () {
return '';
});
Also href="google.no" means go to <currentdomain>/google.no, in case you need the google.no use href="https://google.no"
Check JSFiddle.
Please consider the comments on your question too.

Difficulty hiding image with no src

I have a series of the following elements:
<div class="slidetpl">
<img src >
</div>
I want to hide .slidetpl if the image has no source. To do that I have tried the following:
$('.slidetpl img').each(function () {
if (this.src.length == 0) {
$(this).parent().hide();
}
});
But this is not working.
Can anyone point me in the right direction or tell me what I've done wrong?
This does the effect for me:
// Start an immediate invocable function expression, to auto
// execute the internal code and isolate the code from the
// outside JS scope.
(function( $, window, undefined ){
// Find all the document images and iterate over them. In case you like to
// to iterate only under slidetpl change the selector from
// img to .slidetpl img
$( 'img' ).each(
function() {
// If the empty string is equal with the src attribute of
// of the current item in the iteration
if ( '' === $(this).attr('src') ) {
// Then hide the current item in the iteration.
$(this).hide();
}
}
);
})( jQuery, this )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="" />
<img src />
<img src="http://www.iconsdb.com/icons/preview/icon-sets/web-2-orange-2/running-man-xxl.png" />
Note, the above code will hide all the images with empty src attribute. In case you like to hide only the children elements of the .slidetpl then you can modify the selector from img to .slidetpl img.
Try this:
$(document).ready(function(){
$('.slidetpl img[src=""]').parent().hide();
$('.slidetpl img:not([src=""])').parent().show(); //Can be removed.
});
You are very close, just missing the correct syntax of this, refer below:
if ($(this).attr('src').length == 0)
Watch out the demo here.
$('.slidetpl img[src=""]').hide();

Replace certain html with other html using .html isn't working

I have this html
<div id="items-content">
<p><img class="fr-dib" src="http://i.imgur.com/bEDR9dc.png" data-imgslap="{{image-key}}" style="width: 214px;"></p>
</div>
And i want to replace src="http://i.imgur.com/bEDR9dc.png" with src="http://i.imgur.com/mJyABlG.jpg"
I have the following jquery
$(document).ready(function() {
$('#items-content').html( 'src="http://i.imgur.com/bEDR9dc.png"' ) {
return 'src="http://i.imgur.com/mJyABlG.jpg"';
}
} );
I'm learning JQuery still and I don't know where I have gone wrong. Would appreciate the help.
Update
I plan on using the same method of replacing the image to replace something like data-imgslap= with src=. Basically how do I replace html text 'x' with 'y' (They will only ever be html attributes text being replaced).
Use attr() to solve this problem
$(document).ready(function() { $('#items-content .fr-dib').attr('src', 'http://i.imgur.com/mJyABlG.jpg"'); } );
Or use regular expression
your_string.replace(/(<img\s class\=\"fr-dib\"\ssrc=")(.*?)("\s?\/>)/, "$1http://i.imgur.com/mJyABlG.jpg $3");
Update a DOM img tag's src
You're looking for jQuery's attr() method to update a single attribute's value:
$(document).ready(function() {
$('#items-content .fr-dib').attr('src', 'http://i.imgur.com/mJyABlG.jpg"');
} );
jsfiddle: https://jsfiddle.net/patrickberkeley/0wefe37t/
Update a DOM img src with a value from a data attr
To update one attribute with another attribute's value (in this example updating an image's src with a data attribute's value):
$(document).ready(function() {
var $img = $('#items-content [data-imgslap]');
var newSrc = $img.data('imgslap');
$img.attr('src', 'http://i.imgur.com/' + newSrc + '.jpg"');
} );
jsfiddle: https://jsfiddle.net/patrickberkeley/bx686410/2/
Regex to replace img src in a string
Based on the comments you've left though, it seems like your goal is to a value in a string (rather than updating an img element's src in the DOM).
In order to do that:
var str = '<div id="items-content"><p><img class="fr-dib" src="http://i.imgur.com/bEDR9dc.png" data-imgslap="mJyABlG" style="width: 214px;"></p></div>';
var newSrc = 'http://i.imgur.com/mJyABlG.png';
var newStr = str.replace(/<img(.*)src=[\"|\'](.*?)[\"|\'](.*)/, "<img$1src='" + newSrc + "'$3");
jsfiddle: https://jsfiddle.net/patrickberkeley/qrdt1esz/1/
Notice you *do not $(document).ready() because you're not selecting something from the dom. The above regex should handle: single and double quotes and any combination of attrs on either side of the img's src.

What selector do I use to access this div?

If I have a structure like this:
var myThing = jQuery(
jQuery('<div/>')
.addClass('myTopDiv')
.append(
jQuery('<div/>')
.text('some text')
.addClass('mySecondDiv')
).append('<div/>')
.text('some more text') // I WANT TO REPLACE THIS TEXT
);
How do I target the div which contains the text some more text and replace that text with new text?
I've stored it inside a variable called myThing, but I don't know how to navigate down to the div I want.
I can't use the classes as selectors as there are multiple instances of this variable in my application.
Something like this perhaps? Which doesn't work...
jQuery(
jQuery('<tr/>')
.text('new text')
).appendTo(myThing);
You stop the crazy nesting, and use variables
var topDiv = $('<div />', {
'class' : 'myTopDiv'
}),
secDiv = $('<div />', {
'class' : 'mySecondDiv',
text : 'some text'
}),
thrDiv = $('<div />', {
text : 'some more text'
});
topDiv.append(secDiv, thrDiv);
// change text
thrDiv.text('Some other text');
Not sure but maybe:
jQuery('div.myTopDiv div:last').text()
?
Try this one,
$( "div:contains('John')" )
According to Jquery Documentation it will select the div by it's content
Hope this helps.
You have an error in your code (probably because of complex nesting). check this fiddle http://jsfiddle.net/r1h8fy9j/ for corrected one and two possible solutions for your issue:
jQuery(myThing).find('div:last').text('text to replace to'); - in case if target div is the last one.
jQuery(myThing).find('div').eq(1).text('text to replace to'); - in case if target div is at specific index.

Categories