I want to build such construction using jQuery:
<i class="fa fa-shopping-cart"></i>Add to cart
My jQuery code, which is responsible for this line, looks like that:
var a2 = $('<a>').attr("href", "add_to_cart:" + item['id']).text('Add to cart');
a2.addClass("btn btn-default add-to-cart");
var i1 = $('<i></i>');
i1.addClass("fa fa-shopping-cart");
a2.append(i1);
But result does not contain <i> element.
I tried to append <i> using .html function, but in this case text disappears.
How to make <a> element contain both tag and text after it?
Thanks for your answers
hahaha you forgot the last one...
$(".test").html(a2);
and the parent content
<div class="test"></div>
$(document).ready(function() {
var a2 = $('<a>').attr("href", "add_to_cart:").text('Add to cart');
a2.addClass("btn btn-default add-to-cart");
var i1 = $('<i>iiiiiiiiiiii</i>');
i1.addClass("fa fa-shopping-cart");
a2.prepend(i1);
$(".test").html(a2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
Related
I have a html content in which a span tag is placed inside multiple div tags.
For example :
<div id="ae_launcher" class="module tipsytip active" tabindex="0" role="button" aria-label="" style="display: none;" original-title="">
<div class="left">
<span class="copy-narrow" aria-hidden="true"></span>
</div>
</div>
Also, please note the class "ae-left" has been used 3 times in the entire page.
I need to add text inside the span tag.
I tried something like this:
<script type="text/javascript">
$('.left:eq(1) .copy-narrow').text('hidshjgdjb');
</script>
But this din't solve the issue.
you can do it via jQuery
$('#ae_launcher .ae-left > span ').text("Hello");
Assuming you have used ae-left div class as the parent of the span in all the 3 places
$('.ae-left span ').text("Text here");
<script>
var l = document.getElementsByClassName("ae-copy-narrow");
l[x].innerHTML = "some text";
</script>
x is the location you want to place between 0-2.
You can do it in this way:
$('.left > .copy-narrow').text("your Text");
This will set the innerText property of all elements with
.copy-narrow
class to your Text.
If you want to select this particular span only, you can always use the id attribute of the parent div as id attribute must be unique.
$('#ae_launcher .copy-narrow').text('your text');
You can call the class and use the .text():
<script>
$(function() {
var sometext = 'This is my text';
$('.ae-copy-narrow').text(sometext);
});
</script>
Or if you want to have html tags you can use .html():
<script>
$(function() {
var sometext = '<img src="myimage.png" />';
$('.ae-copy-narrow').html(sometext);
});
</script>
I have got such situation:
<div>
<span id="x1"></span>
<span id="x2"></span>
<span id="x3"></span>
</div>
And I am trying to get something like this:
<div>
<span id="x1"></span>
</div>
<span id="x2"></span>
<div>
<span id="x3"></span>
</div>
I have tried to do that using unwrap() function like this:
$('#x2').unwrap();
But this function removes whole <div>. So how can I do that using jQuery/JavaScript? Thanks for help.
You can unwrap the spans from the common div wrapper and then just wrap x1 and x3 in their own new divs.
$('span').unwrap();
$('#x1,#x3').wrap('<div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span id="x1">x1</span>
<span id="x2">x2</span>
<span id="x3">x3</span>
</div>
If your spans don't have IDs, you could do something like
$('div > span:even').wrap('<div>').parent().unwrap()
Get the all siblings after the target element, wrap them in a new div and put them after the original container.
put the target element between both divs.
This will work for any number of items in the container and will only unwrap the target element.
const el=$("#x2")
const parent =el.parent()
const nextSiblings=el.nextAll()
const newWrap=$("<div>").append(nextSiblings)
parent.after(newWrap)
parent.after(el)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
div{border:solid 1px red;}
span{display:block}
</style>
<div>
<span id="x1">1</span>
<span id="x2">2</span>
<span id="x3">3</span>
</div>
EDIT
add possibility of unwraping more than one element and also handle removal from first or last positions.
const unWrapOne=el=>{
const parent =el.parent()
const nextSiblings=el.last().nextAll()
if(nextSiblings.length>0){
const newWrap=$("<div>").append(nextSiblings)
parent.after(newWrap)
}
parent.after(el)
if(parent.children().length===0)
parent.remove()
}
const unwrapSome = elements => elements.each((index,el)=>unWrapOne($(el)))
unwrapSome($("#x3,#x5")) //unwrap 2 non contiguous elements
//unwrapSome($("#x2,#x3")) //unwrap 2 contiguous elements
//unwrapSome($("#x2")) //unwrap 1 element from middle
//unwrapSome($("#x1")) //unwrap 1 element from begining
//unwrapSome($("#x6")) //unwrap 1 element from end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
div{border:solid 1px red;}
span{display:block}
</style>
<div>
<span id="x1">1</span>
<span id="x2">2</span>
<span id="x3">3</span>
<span id="x4">4</span>
<span id="x5">5</span>
<span id="x6">6</span>
</div>
Here are two of javascript ways:
First one:
Wrap a given element in a new container element using plain JavaScript:
// element that will be wrapped
var el = document.querySelector('#x1');
// create wrapper container
var wrapper = document.createElement('div');
// insert wrapper before el in the DOM tree
el.parentNode.insertBefore(wrapper, el);
// move el into wrapper
wrapper.appendChild(el);
var el2 = document.querySelector('#x3');
var wrapper2 = document.createElement('div');
el2.parentNode.insertBefore(wrapper2, el2);
wrapper2.appendChild(el2);
<div>
<span id="x1">x1</span>
<span id="x2">x2</span>
<span id="x3">x3</span>
</div>
Second one:
Using getElementById
HTMLElement.prototype.wrap = function(wrapper){
this.parentNode.insertBefore(wrapper, this);
wrapper.appendChild(this);
}
var element = document.getElementById('x1');
element.wrap(document.createElement('div'));
var elementx3 = document.getElementById('x3');
elementx3.wrap(document.createElement('div'));
<div>
<span id="x1">x1</span>
<span id="x2">x2</span>
<span id="x3">x3</span>
</div>
//some DOM1 vanilla...
var parent = x1.parentElement;
//var cntnt = parent.children;
//unwrapping the container div with ancient dhtml method
parent.outerHTML = parent.innerHTML;
// wrapping selected elements with jQuery
$("#x1,#x3").wrap('<div>');
// show the end-result HTML
console.log(document.body.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span id="x1"></span>
<span id="x2"></span>
<span id="x3"></span>
</div>
.wrap() and .unwrap() have never worked too well for me. Instead, I usually just wrap the elements outerHTML to wrap and use the innerHTML to unwrap. You mention a list in your comment, that's why I have a select here. Regardless how you select the spans, I think my button handler demonstrates what you are trying to achieve. This also doesn't require unique ids for each span nor does it matter how many you have.
PopulateSelect();
$('button').on('click', function() {
$('select option:selected').each(function(offset, span) {
let $span = $(`span.unwrapped:eq(${span.index - offset})`);
$span.removeClass('unwrapped')[0].outerHTML = `<div>${$span.html()}</div>`;
});
PopulateSelect();
});
function PopulateSelect() {
let options = '';
$('span.unwrapped').each(function() {
options += `<option>${this.textContent}</option>`;
});
$('select').html(options);
}
https://jsfiddle.net/8429pcpu/2/
This is a bit involved, so rather than spamming a bunch of links, feel free to ask about anything you don't understand.
How do you change the name of text within a div that your selector is inside of? In other words, I'd like to click on a button and change the text of the text above the button (within the same div).
For example, in my html, there is a button and a title above it. Once the button is clicked, I'd like the title above it to change to the id of the button.
This problem is similar to this question, but I'm having difficulty changing the text within the div that the selector is in.
Below is my attempt to grab the id of the button, and change the text within the div container.
Javascript (my attempt) (codepen here):
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$('#title').find($(this)).html(desired_name);
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Have you tried $(this).siblings("p")
This will select the <p> above the button
Have you tried jquery .prev()
https://api.jquery.com/prev/
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$(this).prev().html(desired_name);
});
You can use the jQuery method siblings() to select the <p> element inside your <div> container.
However I recommend using a class as a unique selector inside your container.
$('.btn.btn-default').on('click', function() {
$(this).siblings(".desired-name").text($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Change the ID's to classes for starters. Then target them like this:
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id');
$(this).prev(".title").text(desired_name);
});
The URL in div.alpha is dynamic. I need to take this URL and apply it to an 'a href' that wraps 'View Details' in div.beta
<div class="alpha">
Example
Plus some other stuff which may contain links, etc
that I don't want to copy to the other div.
</div>
<div class="beta">
View Details
</div>
Desired result:
<div class="alpha">
Example
Plus some other stuff which may contain links, etc
that I don't want to copy to the other div.
</div>
<div class="beta">
View Details
</div>
I can get the link like this: $('.alpha').find('a').attr('href');
But I don't know how to pass that link to the XXXX below:
$('.beta').each(function(){
$(this).text($(this).text().replace('View Details', 'View Details'));
});
You could clone a.alpha, then just wrap .b's contents with it:
// clone the link, remove the text
$link = $('.alpha').find('a').clone().text('');
// wrap all .beta's contents with the cloned link
$('.beta').contents().wrap($link);
Here's a fiddle
You can achieve the result by updating your code to following.
var href = $('.alpha').find('a').attr('href'); // get href of anchor
var text = $('.beta').text(); // get text of beta element i.e. View Details
var betaHTML = "<a href='" + href + "'>" + text + "</a>"; // Create anchor
$('.beta').html(betaHTML); // Update beta element
If you have several div.alpha and div.beta elements then the best way to achieve this -- it also works for a single pair -- is:
$('div.beta').html(function(i,html) {
return $(this).prev('div.alpha').find('a').clone().html( html );
});
$('div.beta').html(function(i,html) {
return $(this).prev('div.alpha').find('a').clone().html( html );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pair">
<div class="alpha">
Example 1
</div>
<div class="beta">
View Details
</div>
</div>
<div class="pair">
<div class="alpha">
Example 2
</div>
<div class="beta">
View Details
</div>
</div>
var $betaAnchor = $('.alpha a').clone(); //clone anchor
var anchorLabel = $beta.text(); //grab text from beta tag
$('.beta').append($betaAnchor.text(anchorLabel)); //append cloned anchor with beta text
jQuery - Copy a dynamic link from one element to another
CopyLink = jQuery('.page-id-269 ').find('a').clone().attr('href');
jQuery("#menu-item-387 a").attr("href", CopyLink);
Best solution 100% Work
I created a page that displays post with comments using ajax
To view the comments user must click comment button correspond to the post
For simple understanding, example:
In HTML
Block
<button id="btn1">cmt1</button>
<button id="btn2">cmt2</button>
<div id="cmt1">comments</div>
<div id="cmt2">comments</div>
'
I tried of using for loop as
for(var i=0;i<count;i++){
$("#cmt"+i).hide();
$("#cmtbtn"+i).click(function(){
$("#cmt"+i).toggle('slow');
});
}
But It works well for the last cmtbtn only and whenever i click all other buttons last comment box only displays
I'm saying that is there is a way of for loop or any looping
Update: My Js file is here http://jsfiddle.net/9ss50nzc
Try to give a same and unique class to all "Comment Button" and also to "Comment Div". Like example bellow :
<button id="btn1" class="comtbtn"> cmt1 </button>
<button id="btn2" class="comtbtn"> cmt2 </button>
<div id="cmt1" class="comt-div">comments1</div>
<div id="cmt2" class="comt-div">comments2</div>
Then catch the click event on class "comtbtn" . Bellow is the js script to hide show of comment -
$('.comtbtn').click(function() {
var btnId = $(this).attr("id");
var id = btnId.slice(-1);
$( "#cmt"+id ).toggle( "slow" );
});
Add css to hide all the comment section when initially loaded to the DOM.
.comt-div{
display:none;
}
Is this the sort of thing you want? A means of getting the index of the button which is equivalent to the indexed position of the hidden comment on your document?
You just hide the previous comment and display the new comment.
var oldNode = '';
function showComment = function(index) {
if (typeof oldNode != undefined) $(oldNode).hide('slow');
$('.comment:eq('+$(index).index()+')').show();
oldNode = $('comment:eq('+$(index).index()+')');
}
<button onclick="showComment(this)">cmnt 1</button>
<button onclick="showComment(this)" >cmnt 2</button>
<div class='comment' style='display: none'>comment a</div>
<div class='comment' style='display: none'>comment b</div>
Start with giving your buttons and divs classes
<button id="btn1" class="actionButtons">cmt1</button>
<button id="btn2" class="actionButtons">cmt2</button>
<div id="cmt1" class="actionDivs" style="display:none">comments1<br/>more comments<br/>and even more</div>
<div id="cmt2" class="actionDivs" style="display:none">comments2<br/>another comment<br/>and another one</div>
Then loop through elements with that class name
for(var i = 0; i < $(".actionButtons").length; i++){
$(".actionButtons")[i].onclick = function () {
for(var j = 0; j < $(".actionDivs").length; j++){
if ($(".actionDivs")[j].id == this.innerText)
$("#" + this.innerText).show();
else
$("#" + $(".actionDivs")[j].id).hide();
}
};
}
Fiddle
I hope this takes you closer to your solution.
I got the answer it is possible to toggle inside loop by using traversing. Thanks everyone finally I sort out the answer.