Change part of href value based on a parent div attribute - javascript

I have this html
<div class="1" style="" title="NeedthisText TextIDontneed">
<div class="2">
<div class="3">
<a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1">Link</a>
</div>
</div>
</div>
I want to know how can I change "/NeedToChange/" part of the href depending if the title value of the div with class="1" contains some text I need.
Any Help will be greatly appreciated

Classes cannot start with Number! (JS might work but CSS will fail and your document will not validate.)
if "NeedToChange" is something you cannot control you can Regex target and replace any text between slash characters /unknownFolder/, /anything/
$(".1[title]").each(function(){
var title = this.title.split(" ")[0]; // Get only 1st part of title
$(this).find(".3 a").attr("href", function(idx, val){
return val.replace(/^\/([^\/]+)/, "/"+title);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="1" style="" title="SomeText1 I_DONT NEED this">
<div class="2">
<div class="3">
<a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1">Link ID=1</a>
</div>
</div>
</div>
<div class="1" style="" title="WOOOOOW NeitherThis">
<div class="2">
<div class="3">
<a target="_blank" href="/NeedToChange/DispForm.aspx?ID=37">Link ID=37</a>
</div>
</div>
</div>
the above will result in the new hrefs:
/SomeText1/DispForm.aspx?ID=1
/WOOOOOW/DispForm.aspx?ID=1
[title] in $(".1[title]") makes sure that we're targeting .1 (BTW not a valid classs name :) ) element that actually HAS a title.
Than you .find() it's inner .3 Anchor child and access it's .attr("href", property returning a replace using RegExp:
/^\/([^\/]+)/ Explained on regex101.com

You would do it in a way like this:
if ($('.one').attr('title') == 'SomeText1') {
$('a[href*="/NeedToChange/"]').each(function(){
var newLink = $(this).attr('href').replace('/NeedToChange/','/NewLink/');
$(this).attr('href',newLink);
});
}
I changed the class to 'one' since you shouldn't start a class with a number.
Here is an example.

Looping through all of the links and getting the parents title as follow:
jsfiddle
$( ".3 a" ).each(function(){
var $parent = $( this ).closest( ".1" ),
title = $parent.attr( "title" ),
link = "/" + title + "/DispForm.aspx?ID=1";
$( this ).attr( "href", link );
});
This seems to work fine for the following html:
<div class="1" style="" title="SomeText1">
<div class="2">
<div class="3">
<a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1">Link 1</a>
</div>
</div>
</div>
<div class="1" style="" title="SomeText2">
<div class="2">
<div class="3">
<a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1">Link 2</a>
</div>
</div>
</div>
sorry saw the title with a space just now. Will look for update.
update 1:
like Roko C. Buljan mentioned you should probably split the title in an array and get the first element of it.
$('.1').each(function (){
var title = $(this).attr("title"),
clTitle = title.split(" ")[0];
var $link = $(this).find(".3 a"),
href = $link.attr("href"),
newHref = href.replace("NeedToChange", clTitle);
if(typeof $(this).attr('title') !== 'undefined') {
$link.attr("href", newHref);
}
});
updated fiddle: jsfiddle

Related

Jquery pass this.Text() as identifier

Basically im just trying to get the value of this.Text() and edit css of all class with that value.
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">First</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Second</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Third</span> phrase</p>
</div>
Im using this code to get the first word but im a bit lost on how to pass this.Text as indentifier. Im just trying to unhide an image with a class the same with the value of this.Text() :
$('.firstWord').each(function() {
fwtext = $(this).text();
$('#' $fwtext).css("display", "block");
});
The div and all tags inside it are dynamically generated and repeated so i cant simply go on editing them.
THANK YOU SO MUCH EVERYONE FOR HELPING.
This is wrong:
$('#' + $fwtext)
//-----^
Add a + for concatenation. Also since you are using a class and not an id, you must use . instead of #:
$('.' + $fwtext)
Your img tags have a class, not an id. So your jQuery selector should look like: $("." + fwtext). And yes - it will display necessary image only in corresponding div. jsFiddle for testing.
$(".firstWord").each(function () {
var fwtext = $(this).text();
var currentBlock = $(this).parents("div");
currentBlock.find("." + fwtext).show();
});
Remove the $ sign and add + in place of it
$('#'+ fwtext).css("display", "block");
based on your comment here is the edit
$('.firstWord').each(function() {
$('<div></div>').text($(this).text()).css("display", "block");
});

how to get the href of a link when i press another href

i want to get the attr href of an above link beside the one i press wich is the last link from productinfo div class. I tryed with closest but it gets me the same link i press and i want the above one. The link i want to store in produs_href is the link from first href under productinfo class. Here is my code:
<div class="col-sm-4 produse"><!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="/images/produse/'.$recomand['ID_Produs'].'/'.$recomand['Poza'].'" alt="" />
<h2 style="text-decoration: line-through;">'.$recomand['Pret'].' lei </h2><h2>'.$recomand['Pret_Nou'].' lei </h2>
<p>'.$recomand['Nume_Prod'].' '.$recomand['Gramaj'].' '.$tip.'</p>
<i class="fa fa-shopping-cart"></i>Adaugă în coș
</div>
</div>
</div>
</div>
jquery
<script>
$(".cos").click(function(e){
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('a').attr('href');
$.getJSON(href, function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#test").append('<li>' + val.nume + '</li>')
$("#cnt").append('' + val.cnt +'')
});
});
$(\'#detalii_prod\').modal('show');
alert(produs_href);
});
</script>
Use prev. This method gets the immediately preceding sibling.
$(this).prev().attr('href');
EDIT
From your comments, the code that would do the trick is
$(this).closest('.productinfo').find('a:first').attr('href');
You can use the .prev
var link = $(this).prev().attr('href');
and now you can use link.
you can use like this
$(this).prev("a").attr("href");
and more help:
Get the href value of a previous HTML anchoer, <a>, using jQuery
$(".cos").click(function(e){
e.preventDefault();
var text = $(this).parent().find('a:first').attr('href');
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 produse">
<!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center"> <img src="img/Penguins.jpg" height="50" width="50" alt="" />
<h2 style="text-decoration: line-through;">Hello there</h2>
<h2>Anto</h2>
<a href="link produs">
<p>Angeline</p>
</a> <i class="fa fa-shopping-cart"></i>Test </div>
</div>
</div>
</div>
try this
$(this).parent().find('a:first').attr('href');
Try with .eq() method.
$(this).parent().find('a').eq(0).attr('href');
Hope this helps you...

How can I add attributes to an img tag to use in an ajax call

Here is the code I have. This can not be changed, I have to work with the structure as is.
<div class="container">
<div class="contain_box">
<a href="something">
<img class="my_img" src="some_image">
</a>
<div class="variants">
<div class="var" rel="123" data="321"></div>
<div class="var" rel="1234" data="4321"></div>
</div>
</div>
<div class="contain_box">
<a href="something">
<img class="my_img" src="some_image">
</a>
<div class="variants">
<div class="var" rel="456" data="654"></div>
<div class="var" rel="4567" data="7654"></div>
</div>
</div>
<div class="contain_box">
<a href="something">
<img class="my_img" src="some_image">
</a>
<div class="variants">
<div class="var" rel="789" data="987"></div>
<div class="var" rel="7890" data="0987"></div>
</div>
</div>
</div>
What I need is when I click on one of the images it will pull the rel and the data from its first variant, add those attributes to the image tag. Right now I am trying this and I only get the undefined. I am using the undefined to clear out those variables from the current values.
$(document).on("click", '.my_img', function(e){
e.preventDefault();
data = undefined;
rel = undefined;
var new_rel = $('.var').attr('rel');
var new_data = $('.var').attr('data');
$('.my_img').attr('rel', new_rel);
$('.my_img').attr('data', new_data);
data = $(this).attr('variant');
rel = $(this).attr('rel');
}
Any insights or help would be awesome! Thanks in advance!
Find the parent container (.contain_box) relative to the clicked image, then the first variant from there:
Demo
$(document).on("click", '.my_img', function(e){
e.preventDefault();
var firstVariant = $(this).closest('.contain_box').find('.var').first();
data = firstVariant.attr('rel');
rel = firstVariant.attr('data');
$(this).attr({
data : data,
rel : rel
});
console.log(data);
console.log(rel);
});

How to get each element and assign them an inline style contained inside the child

I've been looking for an elegant solution for a day now and I am pretty new to jQuery.
I would like to get each .figure and assign them an inline style where the value is contained inside the child element via a custom data- attribute :
<div>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-01-thumbnail.png" src="images-01.png" />
</div>
<div class="content">
<h3>Sale</h3>
<h4>Discover our latest styles</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-02-thumbnail.png" src="images-02.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-03-thumbnail.png" src="images-03.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
</div>
In other words, the results would be :
...
<div class="figure" style="background: url(images-01-thumbnail.png);">
...
<div class="figure" style="background: url(images-02-thumbnail.png);">
...
<div class="figure" style="background: url(images-03-thumbnail.png);">
...
Also, I'm always ready something about jQuery so if you have any books about JavaScript or jQuery to suggest, that is always appreciated.
You can iterate over all .picture elements, find the image descendant and read its data attribute:
$('.figure').css('background', function() {
return 'url(' + $(this).children('img').data('thumbnail') + ')';
});
Some methods, like .css even accept functions so that you can iterate over the selected elements implicitly.
Reference: .css, .children, .data
you can iterate over each item with the class thumbnail and set the css property to the closet div.
$('.thumbnail').each(function() {
var $this = $(this),
$background = $this.data('thumbnail');
$this.closest('.figure').css({background : $background} )
});
This should work
$("[data-thumbnail]").each(function ()
{
var $this = $(this), url = $this.data("thumbnail");
$this.parents(".figure").css("background-image", 'url("' + url + '")');
});
How about this (Working code example: http://jsfiddle.net/jpbH2/2/):
var pathToImages = "/";
$(".figure img").each(function(){
$(this).parent().css({"background": "url(" + pathToImages + $(this).data('thumbnail') +")"})
});
Edit
I actually didn't notice the data-thumbnail. Edited my answer above

jQuery Newbie, need a little help

Okay, so I am in the process of recreating this feature:
http://www.w3.org/html/logo/#the-technology
I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the <a> and then id="#one" on the <img>), however it is currently not going through each <a> tag and only one. And also it is not removing the class I requested.
Code follows:
JS
$(document).ready(function() {
var container = '#portfolio #text_container';
var img_container = '#portfolio #image_container';
$(container).children('a').bind('click', function() {
var this_attr = $(this).attr('href');
var this_img = $(img_container).find('img').attr('id');
if(this_attr == this_img) {
//$(img_container).find('img').hasClass('current').removeClass('current');
// ^^^ This line isn't working, any ideas? :/
$(img_container + ' img[id*="' + this_attr + '"]').addClass('current');
}
else {
alert(this_img + ' this img');
alert(this_attr + ' this attr');
}
});
});
And the HTML is as follows
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
</div>
<div id="text_container">
Item 1
Item 2
<p id="#one" class="current">A bunch of text!</p>
<p id="#two">The second bunch of text!</p>
</div>
</div>
Please let me know if you need any more information :)
rcravens fixed this with the following code..
JS
$(document).ready(function() {
$('#text_container a').click(function(evt) {
evt.preventDefault();
$('.current').removeClass('current');
var href = $(this).attr('href');
$("." + href).addClass('current');
});
And the HTML..
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
</div>
<div id="text_container">
Item 1
Item 2
<p class="one current">A bunch of text!</p>
<p class="two">The second bunch of text!</p>
</div>
</div>
My interpretation of what you are trying to do is here:
http://jsfiddle.net/rcravens/wMhEC/
The code is changed a bit. You shouldn't have multiple elements with the same id.
Bob
The reason this isn't working:
if(this_attr == this_img)
is because this_attr is a URL and this_img is an ID attribute value.

Categories

Resources