How to access an element that is placed next to it? - javascript

I have following html structure:
<span class="thump">1</span>
<a class="tp" href="#" programm="5">Post</a>
Now I want to write thump according to programm attribute. This is how I get the the a element according to the programm number:
$("a.tp[programm='" + programm + "']");
How do I refer to the thump element that is next to this a element?

var anchor = $("a.tp[programm='" + programm + "']");
var thump = anchor.prev();
Or if there is only one thump element (previous is recommended, especially if they are adjacent elements):
var anchor = $("a.tp[programm='" + programm + "']");
var thump = anchor.siblings('.thump');

Related

Placing generated JavaScript URL into `<a href="{{Text here}}">`

So, I have an external JavaScript that generates 4 numbers and puts them between 2 parts of text, like this
document.getElementById("gen3").textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669";
<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<div id="gen3"></div>
It generates properly and selecting it and opening it in a new tab works perfectly, but I'd like to make it easier by placing it directly into an href.
You can change your div into an a (anchor tag) in your HTML and use its href property in JavaScript to set the URL destination used when you click it. You can also choose to set its textContent to the same value, which makes it clearer to people using the tool where exactly they are going when they click the link.
gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
Demo Snippet
var gen3 = document.getElementById("gen3")
function postmessage() {
// Pretending these are "random" values, and assuming you have the code for them already
var first = 1,
fnum = 2,
snum = 3,
tnum = 4
// Later...
gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
}
<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<p>
<a id="gen3"></a>
</p>
You can create an anchor tag inside the div
Then you can do like this
JS
document.getElementById("linkText").setAttribute('href','www.google.com')
HTML
<div id="gen3">
Click Me
</div>
DEMO

jQuery .html() function removing text

I am trying to edit the div's text, but when i use my function to update the rowcount, everytime the text vanihes completely. Would by nice if you could also explain why.
Thanks in advance.
My update function:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + String(rowCountF) + ")";
var vtext = "Teilnehmer (" + String(rowCountV) + ")";
$("#divf").html(ftext);
$("#divv").html(vtext);
My div layer:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
Code for divf:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
You are actually replacing the contents of the div itself with your text. This means the heading disappears and there is only plain text.
Probably you wanted to replace the heading contents:
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
This will select the h2 elements inside the divs and hence will update only the text inside the headings.
The result will look like the following:
<div id="divf"class="tableheader"> <h2>Teilnehmer (987)</h2> </div>
<div id="divf"class="tableheader"> <h2>Teilnehmer (123)</h2> </div>
.html() sets the HTML, meaning it replaces anything that's currently there. If you want to add to the HTML, you'll need to set the HTML to what's already there plus what you're adding, like so:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + rowCountF + ")";
var vtext = "Teilnehmer (" + rowCountV + ")";
//Get already-existing HTML
var divfHtml = $("#divf").html();
var divvHtml = $("#divv").html();
//Set the new HTML to the existing + the new text
$("#divf").html(divfHtml + ftext);
$("#divv").html(divvHtml + vtext);
If you only want to replace the heading, then just target the <h2> as Martin Zikmund suggested in his answer.
You need to reference the h2 for the div. using .html() will replace ALL of the html inside the #divf which in this case means it will replace the h2
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
Example: https://jsfiddle.net/qhef0toc/3/

How to set different <a href> and <img src> dynamically in divs with same class name?

I have an array of objects(each that are made up of image link and link). As I access each of them I would like to make a new div each time and add a different image link and link.
<div class="igo_product"
<a href>
link1
<img class="igo_product_image" src="imglink1">
</div>
<div class="igo_product"
<a href>
link2
<img class="igo_product_image" src="imglink2">
</div>
<div class="igo_product"
<a href>
link3
<img class="igo_product_image" src="imglink3">
</div>
Currently the only way I can place different images and links is by creating different class names by concatenating indexes at the end each time.
$.each(items, function (index, value) {
$(".igo_boxbody").append('<div class="igo_product' + index + '"<a><img class="igo_product_image' + index + '"></a></div>')
$(".igo_product" + index + "a").attr('href', value["link"].toString());
$(".igo_product_image" + index).attr('src', value["image_link"] );
});
However, $(".igo_product" + index + "a").attr('href', value["link"].toString()); does not correctly set my href...I'm assuming it's my way I'm concatenating the class, index, and a but I'm slightly stuck on what else I can do. Also, is there a better way to do this? I would rather keep the class name the same so that I can apply styles to all these classes easier.
How about this:
$.each(items, function (index, value) {
$(".igo_boxbody").append('<div class="igo_product"<a href="'+value["link"].toString()+'"><img class="igo_product_image" src="'+value["image_link"]+'"></div>');
});
There is an error:
$(".igo_boxbody").append('<div class="igo_product' + index + '"<a><img class="igo_product_image' + index + '"></a></div>')
//-----------------------------------------------------------^---no closing of div >
so change to this:
$(".igo_boxbody").append('<div class="igo_product' + index + '"><a><img class="igo_product_image' + index + '"></a></div>')
Should go for this:
$.each(items, function (index, value) {
var el = '<div class="igo_product"' + index
+ '><a href="'+value["link"]
+'"><img class="igo_product_image' + index
+ '" src="'+value["image_link"]+'"></a></div>'
$(".igo_boxbody").append(el);
});
By no means I intend to imply the following is better, but just to mention the option: you can use jquery to create html objects outside the DOM (e.g. $('<div>') creates a new div) and set their properties/attributes/classes/etc through those objects (also before adding them to the DOM).
The advantage is that you don't have to delve into the strings to catch those closing tags:
$('.igo_boxbody').append(items.map(function(value, index){
return $('<div>').addClass('igo_product').append(
$('<a>').attr('href', value.link).append(
$('<img>').attr('src', value.image_link).addClass('igo_product_image' + index)
)
);
}));
Fiddle

How to get specific span's value from div in JQuery

I have a div and i want to get text of a specific span from that div.
Following is my Div code:
'<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid + '">' + count + '</span><span id="pname" style = "margin-left:70px;">' + pname + '</span><span id="punitprice" style = "margin-left:150px;">' + uprice + '</span></div>'
and i want to get text of the following span:
<span class="count_' + pid + '">' + count + '</span>
Please help me how to do it .
The span element which you want to target have next sibling with id. you can target that element using id selector and traverse to required span using .prev():
$('#pname').prev().text()
If you know the pid of the span you want to get, you can use
$('.count_' + pid).text()
You can identify pname element using ID selector then use .prev() to identify the desired span
$('#pname').prev().text()
Using find you can get value of span through div
function findSpanValue(pid){
return $(".dvDynamic_"+pid).find(".count_"+pid).text();
}
Get span element to target have next sibling with id. you can get that element using id selector and traverse to required span using .prev():
$('#pname').prev().html();
or
$('#pname').prev().text();

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

Categories