how to dynamically set text to an element in jquery - javascript

i have an onclick function that that calls a changeName function anytime a click event on that element happens.
function changeName() {
var frag = $('<span class="Name">change me</span>');
$( ".list" ).prepend(frag);
var x =[];
$('.ch-gname').each(function(index, obj)
{
x.push($(this).text());
for(i=0; i<x.length; i++) {
$('.Name').text(x[i]);}}});
$('#action').on('click', changeName);
HTML
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">Greenhouse</span>
</div>
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">tree house</span>
</div>
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">light house</span>
</div>
<div class="list">
</div>
<div class="list">
</div>
<div class="list">
</div>
i want to able to change the text of the class Name to the text of class ch-gname. My function gives me only the last text text(lighthouse) for the three links.Any help please

The function changeName() has $('#action').on('click', changeName); but i do not see any element with id 'action'. Anyhow i've made necessary changes in order to make it work.
Added Action id to the elements
Changed the $('.Name').text(x[i]); to $('.Name')[i].innerHTML = x[i];
Look at the below example
function changeName() {
var frag = $('<span class="Name">change me</span>');
$(".list").prepend(frag);
var x = [];
$('.ch-gname').each(function(index, obj) {
x.push($(this).text());
});
for (i = 0; i < x.length; i++) {
$('.Name')[i].innerHTML = x[i];
}
}
$('#action').on('click', changeName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">Greenhouse</span>
</div>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">tree house</span>
</div>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">light house</span>
</div>
<div class="list">
</div>
<div class="list">
</div>
<div class="list">
</div>

Related

I want to hide all element with <a> tag and contain a link

Please I want to hide <a> that contains a link sabdel.com .
I used the below javascript code but it doesn't work
window.addEventListener=()=>{
var elem=document.querySelectorAll("a");
var i;
for(i=0;i<elem.length;i++){
var obj=elem[i];
if(obj.innerHTML.toString().includes('sabdel.com')){
obj.style.display="none";
}
}
}
<div>
<div>
<div>
<div>
<img src="//ae01.alicdn.com/kf/Haabbc1065ea449668ced4bf88021f4aea.png">
<p></p>
<div style="margin-left:36.847599164927%;margin-top:-30.27139874739%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000105891117.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-left:57.306889352818%;margin-top:-29.958246346555%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000147845779.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-left:77.76617954071%;margin-top:-29.958246346555%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000990281325.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-top:0.31315240083507%;height:0;width:0"></div>
</div>
<div>
<img src="//ae01.alicdn.com/kf/H69979517a8a248e9a84aec8986854e277.png">
<p></p>
<div style="margin-left:1.5657620041754%;margin-top:-31.524008350731%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4000985761425.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:26.096033402923%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4000224026872.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:50.62630480167%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/1005001597400364.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:75.156576200418%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4001044974112.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-top:0.73068893528184%;height:0;width:0"></div>
</div>
First of all, you are incorrectly using addEventListener. Second, you must check the href attribute, not innerHTML:
window.addEventListener("yourEvent", () => {
var elem=document.querySelectorAll("a");
for(var i = 0; i < elem.length; i++) {
if(elem[i].href.includes('sabdel.com')) {
elem[i].style.display="none";
}
}
}
Replace yourEvent with the event you want to listen with. For example, if you are listening for a click event, replace it with click.
Do you mean like this ?
window.addEventListener = () => {
var tags = document.getElementsByTagName("a");
for (var i = 0; i < tags.length; i++) {
var attributeValue = tags[i].getAttribute('href');
if (attributeValue.includes('sabdel.com')) {
tags[i].style.display = 'none';
}
}
}

How to create a data object from the list of displayed element in the html

My html is like below:
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_1" />
</div>
</div>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_2" />
</div>
</div>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_3" />
</div>
</div>
Using jquery, I want to create an object like following from the above HTML:
[
{
position :1,
url: "https://link_to_Item_1"
},
{
position :"2",
url: "https://link_to_Item_1"
},
{
position :"3",
url: "https://link_to_Item_2"
}
]
I tried something like below:
var myData = [];
var myDataElements = {};
$('.list-item').find('a').each(function(index, ele){
myDataElements.position = index;
myDataElements.url = $(this).attr('href');
myData.push(myDataElements);
});
But the result was the position and URL became the same for all elements in myData.
The issue is you are declaring the object outside. But you need the object in each iteration, declare that inside the function:
var myData = [];
$('.list-item').find('a').each(function(index, ele){
var myDataElements = {};
myDataElements.position = index + 1;
myDataElements.url = $(this).attr('href');
myData.push(myDataElements);
});
console.log(myData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_1" />
</div>
</div>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_2" />
</div>
</div>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_3" />
</div>
</div>
You can also use jQuery's .map() and .get() like the following way:
var myData = $('.details').map(function(i, el){
return {
position: i+1,
url: $(el).find('a').attr('href')
}
}).get();
console.log(myData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_1" />
</div>
</div>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_2" />
</div>
</div>
<div class="list-item">
<div class="details">
<a href="https://link_to_Item_3" />
</div>
</div>
You need to initialize the variable myDataElements inside the loop :
var myDataElements = {};
And make sure you're closing the anchor tag well like :
Instead of :
<a href="https://link_to_Item_1" />
NOTE: You can increase the index by 1 if you want to start counting from 1 instead of zero since the index is zero-based.
var myData = [];
$('.list-item a').each(function(index, ele) {
var myDataElements = {};
myDataElements.position = index + 1;
myDataElements.url = $(this).attr('href');
myData.push(myDataElements);
});
console.log(myData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="details">
</div>
</div>
<div class="list-item">
<div class="details">
</div>
</div>
<div class="list-item">
<div class="details">
</div>
</div>
myDataElements here pointing to the same object. And with each iteration you are basically changing the value of its 2 properties, position and url and then pushing it to the array. All array elements of myData are same object which you created here var myDataElements = {};. That's is why you ended up with same objects in myData.
What you want here is:
myData.push(Object.assign({}, myDataElements);
// or myData.push({...myDataElements});
Now you are creating a new object by copying the myDataElements before pushing it it the array myData. This gives you the desired output.

How to hide an element based on another existing

I have a jQuery code that looks for a specific div element.
If the element exist I define a variable and use parseFloat() function. Since there are going to be more than one element with the same class I've created an array.
So far I've managed to hide the element called: div.ifc-balance-div; however I am not quite sure how I can hide the div.ribbon-yellow, in case the element does not have the variable savePrice.
(function($) {
"use strict";
$(document).ready(function() {
var j = 0,
savePrices = jQuery('.special-price .price .price').map(function() {
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
if(j < savePrices.length){
++j;
}
for (var i = 0; i < savePrices.length; ++i) {
if (Number(savePrices[i]) > 0) {
var ifcBalance = Number(savePrices[i]) / 1,
m = parseFloat(ifcBalance).toFixed(0);
$('div.ifc-balance-div' + (i + 1)).html('<p class="dynamic-badge-txt"><b>£' + m + ' OFF</b></p>');
$('div.ribbon-yellow').html('<div class="badge-ends-message">ENDS TUESDAY</div>');
}
else {
$('div.ifc-balance-div' + (i + 1)).hide();
}
}
});
})(jQuery);
Here is a sample of the HTML Code:
one having Save Price:
Text
<div class="price-box">
<p class="old-price">
<span class="price-label">Was</span>
<span class="price" id="old-price-15510">
<span class="price"><span class="currency">£</span>599</span> </span>
</p>
<p class="special-price">
<span class="price-label">You Save</span>
<span class="price" id="price-excluding-tax-15510">
<span class="price"><span class="currency">£</span>300</span> </span>
</p>
</div>
From
£299
One without save price:
<div class="ribbon-yellow"></div>
<div>
</div></div></div>
<a href="#" title="#">
<img src="#" alt="#">
</a>
</div>
<div class="item__detail">
<a href="#" title="#" class="item__link">
<p class="product-name item__name">Text</p>
</a>
<div class="price-range">
<span class="price-label">From </span>
<span class="price"><span class="price"><span class="currency">£</span>299</span></span>
</div>
</div>
</div>

how to create generic html with javascript

I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.

Conditional innerhtml change

Let's say I have an HTML structure like this:
<li id="jkl">
<div class="aa">
<div class="bb">
<div class="cc">
<div class="dd">
<a ...><strong>
<!-- google_ad_section_start(weight=ignore) -->Test
<!-- google_ad_section_end --></strong></a>
</div>
</div>
</div>
<div class="ee">
<div class="ff">
<div class="gg">
<div class="excludethis">
<a...>Peter</a>
</div>
</div>
</div>
</div>
</div>
</li>
My goal is to set the content(innerhtml) of <li id="jkl"> to '' if inside of <li id="jkl"> there is any word of a list of words(In the example below, Wortliste) except when they are in <div class="excludethis">.
In other words, ignore <div class="excludethis"> in the checking process and show the html even if within <div class="excludethis"> there are one or more words of the word list.
What to change?
My current approach(that does not check for <div class="excludethis">)
Wortliste=['Test','Whatever'];
TagListe=document.selectNodes("//li[starts-with(#id,'jk')]");
for (var Durchgehen=TagListe.length-1; Durchgehen>=0; Durchgehen--)
{
if (IstVorhanden(TagListe[Durchgehen].innerHTML, Wortliste))
{
TagListe[Durchgehen].innerHTML = '';
}
}
with
function IstVorhanden(TagListeElement, Wortliste)
{
for(var Durchgehen = Wortliste.length - 1; Durchgehen>=0; Durchgehen--)
{
if(TagListeElement.indexOf(Wortliste[Durchgehen]) != -1)
return true;
}
return false;
}
Only has to work in opera as it's an userscript.

Categories