jquery get p and span data and place in variables - javascript

<div class="pricecard aircraft">
<div class="card-body">
<p>One way<br>
<span class="onewayaircraftprice">£492.00</span></p>
</div>
</div>
How can I use jquery to use the data in the p tag in to 2 variables?
ie
var1 = "One Way"
var2 = "£492.00"
my code
// This returns both data :(
var1 = $(this).children('.card-body').find('p').text());

First option is to wrap one way by any tag. Then it's simple. Eg. span:eq(0) and span:eq(1).
// This returns both data :(
var span = $('.card-body').find('span:eq(1)').text();
var text = $('.card-body').find('span:eq(0)').text();
console.log(span)
console.log(text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricecard aircraft">
<div class="card-body">
<p><span>One way</span><br>
<span class="onewayaircraftprice">£492.00</span></p>
</div>
</div>
With your current HTML markup you can use for example this one
// This returns both data :(
var span = $('.card-body').find('span').text();
var text = $('.card-body').find('p').text().replace(span, '');
alert(text); // One way
alert(span); // £492.00

Related

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

Get the value of an element child in javascript

I'm trying to get the value of an element child. Here is the element :
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>
I would like to get the value of <p></p>, if possible in javascript. I've tried to use
document.getElementById(1).childNodes[1].nodeValue;
and
var o = document.getElementById(i).children
o[1].nodeValue
Nothing worked, the alert always returns null.
Since you've specified jQuery:
$('#1 p').text();
As simple as that.
You can use following:
innerText || textContent
These will give you text of element. If you have nested elements like a small tag inside p, you will get text of all.
innerHTML
This will return HTML of the element. If you have nested elements, it will not return text, but a raw html of that element. But if element does not have a child, then output will be same.
(function() {
var parent = document.getElementById('1');
var _innerText = parent.innerText;
var _innerHTML = parent.innerHTML;
var _textContent = parent.textContent;
console.log(_innerText, _innerHTML, _textContent)
})()
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>
Try:
var pString = document.getElementById("ihi").value;
and to change the value:
pString.innerHTML = "Your string"
with JS
alert(document.getElementById('ihi').innerHTML)
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>
with JQUERY:
alert($('#ihi').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>
You can use the innerText property:
alert(document.getElementById(1).childNodes[1].innerText);
// Alerts "--"
In case you want to use jQuery:
alert($("1").child("#ihi").html())

Create custom variable names

I have an orientational question that i'm not quite sure how to approach, so this is a request for advice.
For a project i'm working on i would like to assemble 'custom' variable names. For example, lets say i have this html page:
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Now i know i can get the id's in jQuery with $('div').attr('id'). This is where my problem comes in:
I would like to create something like this line:
var variable_name_custom = 'Hello world';
where the var-name is generated by getting the div id's. (string div 1 + string div 2 + string div 3).
If i were to put the 3 names together right now, i would get the string 'variable_name_custom', but it would be a string-value of a variable, rather than the name of one.
Is this possible?
I have no idea why you would want to do something like this but:
var varName = getName(); // will get you 'div1_div2_div3'.
window[varName] = 'Hello world';
alert(div1_div2_div3); // Hello World.
Now you can access the div1_div2_div3 global var you created.
Take a look at this Fiddle
Here you go: http://jsfiddle.net/lotusgodkk/wd99s/
window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')] = 'Sample';
console.log(window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')]);
<div id="variable"></div>
<span id="name"></span>
<p id="custom"></p>
I think your best bet is to change the var into a property of an object.
names = {};
names[id1+'_'+id2+'_'+id3] = 'Hello world';
Hi you can use map function of Jquery
HTML Code
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Javascript
$(document).ready(function () {
var varname = $("#content > div").map(function () {
return this.id || null;
}).get().join("_");
window[varname] = "Hello World";
console.log("varname = "+varname);
console.log("value = "+window[varname])
});
take a look at this fiddle
Hope this helps
Thanks,
Dhiraj

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources